4

I've found some examples of doing this in similar situations, but this is the only shell-script I've written that does anything besides run commands verbatim, so I am struggling to apply the examples to my own situation and need some hand-holding <3

I'm just trying to batch rip audio from MP4s. This script works:

for f in *.mp4; 
    ffmpeg -i "$f" -f mp3 -ab 192000 -vn "mp3s/$f.mp3"
done

But the files all end with .mp4.mp3. How can I get rid of the mp4 part?

2 Answers 2

12

If you're using bash

${f%%.mp4}

will give the filename without the .mp4 extension.

Try using it like this:

for f in *.mp4; do
    ffmpeg -i "$f" -f mp3 -ab 192000 -vn "mp3s/${f%%.mp4}.mp3"
done

... and don't forget the do keyword as in the example given.

Explanation

The bash Manual(man bash) states:

${parameter%word} ${parameter%%word}

Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the %'' case) or the longest matching pattern (the%%'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

This is just one of many string manipulations you can perform on shell variables. They all go by the name of Parameter Expansion.

That's as well the section label given in the bash manual. Thus man bash /paramter exp should bring you there fast. `

Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I needed and it works great, thanks! If you wouldn't mind though could you describe briefly what ${f%%.mp4} means or what that sort of operation is called so I can look it up? Will accept answer as soon as it allows me to.
According to your feedback I added the explanation to my post. As I already stated there Parameter Expansion is the term you might want to lookup in the bash manual.
0

Following command to change file extension for all files under the current directory.

find . -depth -name "*.c" -exec sh -c 'dname=$(dirname {}) && fname=$(basename {} .c) && mv {} $dname/$fname.h' ";"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.