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.

  • for i in *.mp3 do mv $i "${i%.mp3}_p192.mp3"; done This will also not work. – Leo Zerino Jun 10 '17 at 4:11
  • 2
    It's doing what you are telling it to do: printf '%s\n' has to be changed to mv "$f" once you have confirmed it works... – jasonwryan Jun 10 '17 at 4:11
  • ok, now i see where I was being dumb. thank you a lot. – Leo Zerino Jun 10 '17 at 4:39

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"
| improve this answer | |

You can use the rename command. For example to add the text "_p192" before the file extension you can try: rename -n 's/(.*)\.mp3/$1_p192.mp3/' *.mp3.

The above command will rename all files with .mp3 extension in the current directory. The command will only print the renamed files to console. To actually rename the files, remove the -n flag.

The 's' modifier indicates substitution. The first part of the substitution is the regular expression for matching text within a file name. The second part is the replacement text. The final argument to the rename command is a glob pattern for indicating which files to rename

| improve this answer | |
  • While you are linking to the man page for the command from util-linux, it looks like you are referring to the perl rename. There are historically two distinct lines of it. – fra-san Apr 12 '19 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.