How to rename multiple files quickly with rename utility

Batch rename with rename utility

One of the very useful utility in Linux/Unix based system call rename make it so easy to rename multiple files at once.

Recently I have some file that have some kind of patterns that I like to rename to.

e.g. I like to make sure that my audio files are sorted properly so that they play in the right order in iTune

some-file-001.mp3  => 001-some-file.mp3
other-file-002.mp3 => 002-other-file.mp3
more-file-003.mp3  => 003-more-file.mp3

Here is the how to do it with rename utility

The setup

brew install rename

After this is done you should see something like this if you use brew info

rename: stable 1.600 (bottled), HEAD
Perl-powered file rename script with many helpful built-ins
/opt/boxen/homebrew/Cellar/rename/1.600 (3 files, 40.3K) *
  Poured from bottle

Now we are ready to start using this utility

To get the list of options just type the rename which you should see something like:

    rename [switches|transforms] [files]


    -0/--null (when reading from STDIN)
    -f/--force or -i/--interactive (proceed or prompt when overwriting)
Wide character in print at /System/Library/Perl/5.18/Pod/ line 286.
    -g/--glob (expand "*" etc. in filenames, useful in Windows™ CMD.EXE)
    -l/--symlink or -L/--hardlink

    Transforms, applied sequentially:

    -s/--subst *from* *to*
    -S/--subst-all *from* *to*
    --camelcase --urlesc --nows --rews --noctrl --nometa --trim (see manual)

Once you understand the basic of the command then things are very simple:


For my use case above

$mkdir -p "samples"
$touch samples/first-file-001.mp3
$touch samples/second-file-002.mp3
$touch samples/third-file-003.mp3

Now let’s try to rename them

$rename -n 's/(.*)-(\d{3,})/$2-$1/' *.mp3
'first-file-001.mp3' would be renamed to '001-first-file.mp3'
'second-file-002.mp3' would be renamed to '002-second-file.mp3'
'third-file-003.mp3' would be renamed to '003-third-file.mp3'

And to commit it just ignore the -n options

rename 's/(.*)-(\d{3,})/$2-$1/' *.mp3
'first-file-001.mp3' would be renamed to '001-first-file.mp3'
'second-file-002.mp3' would be renamed to '002-second-file.mp3'
'third-file-003.mp3' would be renamed to '003-third-file.mp3'

You file should now look like


Happy hacking!

Useful Links

comments powered by Disqus