Bash – Add text to end of the filename but before extension

bashrename

I have several mp3's that i need to add '_p192' before the extension.

I've tried this :

for f in *.mp3; do printf '%s\n' "${f%.mp3}_p192.mp3"; done

following this post:

adding text to filename before extension

But it just prints the file names to stdout without actually renaming the files.

Best Answer

The answer that you looked at was for a question that did not ask for the actual renaming of files on disk, but just to transform the names of the files as reported on the terminal.

This means that you solution will work if you use the mv command instead of printf (which will just print the string to the terminal).

for f in *.mp3; do mv "$f" "${f%.mp3}_p192.mp3"; done

I'd still advise you to run the the printf loop first to make sure that the names are transformed in the way that you'd expect.

It is often safe to just insert echo in front of the mv to see what would have been executed (it may be a good idea to do this when you're dealing with loops over potentially destructive command such as mv, cp and rm):

for f in *.mp3; do echo mv "$f" "${f%.mp3}_p192.mp3"; done

or, with nicer formatting:

for f in *.mp3; do
    echo mv "$f" "${f%.mp3}_p192.mp3"
done