The officially official Devuan Forum!

You are not logged in.

#1 2022-09-19 15:03:58

Camtaf
Member
Registered: 2019-11-19
Posts: 215  

Convert mp4 to mp3

Convert mp4 to mp3

I have a load of mp4 files with spaces in their names, the first line replaces the spaces with _ so that the second line can convert them to mp3.

#!/bin/sh

for f in *; do mv "$f" `echo $f | tr ' ' '_'`; done

for X in *.mp4;do ffmpeg -i $X $X.mp3;done

Offline

#2 2022-09-19 15:26:46

Head_on_a_Stick
Member
From: London
Registered: 2019-03-24
Posts: 2,532  

Re: Convert mp4 to mp3

The second line can work with spaces in the filenames as long as you double-quote the variables, like this:

for X in *.mp4;do ffmpeg -i "$X" "$X".mp3;done

Unless you actually want to remove the spaces anyway.

To remove the spaces with bash use

for f in *\ *.mp3; do mv "$f" "${f// /_}" ; done

The "${f// /_}" bit uses bash's parameter expansion mechanism to search and replace the given pattern.

See https://wiki.bash-hackers.org/syntax/pe … nd_replace for more on this. It won't work with /bin/sh though.

EDIT: oh, hello Keith. Didn't realise it was you :-)

Last edited by Head_on_a_Stick (2022-09-19 15:40:31)

Offline

#3 2022-09-20 15:06:21

Camtaf
Member
Registered: 2019-11-19
Posts: 215  

Re: Convert mp4 to mp3

Yep, it's me again.... big_smile

Thanks for the extra info though, this kind of thread gets read by more than those who post them, so any extra is always welcome.

Offline

#4 2022-09-22 13:45:12

Head_on_a_Stick
Member
From: London
Registered: 2019-03-24
Posts: 2,532  

Re: Convert mp4 to mp3

I really should have spotted this but victorvas over at daemonforums noticed that the output files need the ".mp4" bit stripping before adding the ".mp3" suffix, so:

for X in *.mp4; do ffmpeg -i "$X" "${X%.mp4}".mp3; done

EDIT: moved second close quote to before the dot. Meh.

Last edited by Head_on_a_Stick (2022-09-22 13:48:24)

Offline

#5 2022-09-22 14:47:36

Camtaf
Member
Registered: 2019-11-19
Posts: 215  

Re: Convert mp4 to mp3

Yes, I had to remove the .mp4 too, again, I used sed.

##To remove .mp4 from *.mp4.mp3 files
for file in *; do mv "$file" $(echo "$file" | sed -e 's/.mp4././g'); done

Offline

#6 2022-09-22 16:57:20

xinomilo
Member
Registered: 2017-07-02
Posts: 267  

Re: Convert mp4 to mp3

how about this:

find . -type f -name '*.mp4' -exec bash -c 'ffmpeg -i "$0" "${0/%mp4/mp3}"' '{}' \;

i've had this for ages (copied from some gist someplace), still works fine afaik.

Offline

Board footer