13

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.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

2 Answers2

18

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
Kusalananda
  • 333,661
3

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

fra-san
  • 10,205
  • 2
  • 22
  • 43
Nadir Latif
  • 237
  • 2
  • 4