Search code examples
bashechospaceglobmv

Glob renaming in bash


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.


Solution

  • 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).