Rename numbered files

Sometimes you have a bunch of files, for example a bunch of images, which name consists of just a number and an extension. When you want to process them further sorting them will sometimes fail when they are not prefixed with a zero. That’s easily solved in a one-liner

Under *nix systems the files are easily renamed to contain a prefix. The trick to do this is using printf and specifying a format. Below an one-liner, which exactly does that using the Bash shell.

for i in $(seq 20);do j=$(printf "%.3d" $i);mv $i.jpg $j.jpg;done

The for loop will run from 1 – 20 and renames (moves) the file from it’s original name to one with a prefix to make the number always use 3 positions.

So a list of files that consists of:

Pulsar:~$> ls
1.jpg 10.jpg 11.jpg 12.jpg 13.jpg 14.jpg 15.jpg 16.jpg 17.jpg 18.jpg 19.jpg 2.jpg 20.jpg 3.jpg 4.jpg 5.jpg 6.jpg 7.jpg 8.jpg 9.jpg
Pulsar:~$>

Becomes after running the command:

Pulsar:~$> ls
001.jpg 002.jpg 003.jpg 004.jpg 005.jpg 006.jpg 007.jpg 008.jpg 009.jpg 010.jpg 011.jpg 012.jpg 013.jpg 014.jpg 015.jpg 016.jpg 017.jpg 018.jpg 019.jpg 020.jpg
Pulsar:~$>

And all of that in just one line 😉