7

I'm fairly new to bash so sorry if this is kind of a basic question. I was trying to rename a bunch of mp3 files to prepend 1- to their filenames, and mv *.mp3 1-*.mp3 didn't work unfortunately. So I tried to script it, first with echo to test the commands:

for f in *.mp3 ; do echo mv \'$f\' \'1-$f\'; done

Which seems to output the commands that I like, so I removed the echo, changing the command to

for f in *.mp3 ; do mv \'$f\' \'1-$f\'; done

Which failed. Next I tried piping the commands onward like so

for f in *.mp3 ; do echo mv \'$f\' \'1-$f\'; done | /bin/sh

Which worked, but if anyone could enlighten me as to why the middle command doesn't work I would be interested to know. Or if there is an more elegant one-liner that would do what I wanted, I would be interested to see that too.

wim
  • 338,267
  • 99
  • 616
  • 750

2 Answers2

9

I think you have to change the command to

for f in *.mp3 ; do mv "$f" "1-$f"; done

Otherwise you would pass something like 'file1.mp3' and '1-file1.mp3' to mv (including the single quotes).

bmk
  • 13,849
  • 5
  • 37
  • 46
  • i intended to include the single quotes, because otherwise i would need to escape all the spaces with backslashes. mv does not mind the quotes. however, the filenames can also have ' in them (and " for that matter). – wim May 04 '11 at 12:09
  • You don't need to escape the spaces when you use double quotes around `$f`. It's also no problem if the file name contains single or double quotes. – bmk May 04 '11 at 12:28
9

Dry run:

rename -n 's/^/1-/' *.mp3

Remove the -n if it looks correct to run the command. man rename for details.

l0b0
  • 55,365
  • 30
  • 138
  • 223
  • 2
    This works on Debian but not on CentOS where the rename command does not follow this syntax and is much less powerful. – Jean Paul May 29 '17 at 10:51