Rename all files and images using Mac Terminal

Posted by: Alex on November 9, 2014

Ever had a folder of images with completely random file names and just wished they were all in a clean numeric order, eg: 1.jpg, 2.jpg etc.

This code byte is a simple way of achieving just that.

Fire up your Mac Terminal and follow the following steps:

Open Applications>Utilities>Terminal.app.

And follow the code byte below, basically you CD (Change directory) so terminal is looking at the folder you want to make changes to and then pretty much copy-paste the single line loop. It will rename files into the 00n.fileExtension format. Eg: 001.jpg, 002.jpg, 003.png.

cd ~/yourfolderlocation/path/imagesarehere/
// (Or type cd and then drag the folder onto terminal

i=1; for f in *; do mv "$f" $(printf %03d $i).${f#*.}; let i++; done

Explanation:
for each file found; do “move” filename variable”; done loops over your files. file is the variable that holds filenames.

n, initially set to 1 and increased by one in every iteration with let n++, is the integer suffix for the renamed files.

If you wish to get fancier and control the naming structure it’s this line that handles the naming:
$(printf %03d $i).${f#*.}
Where %03d $i is 001 and .${f#*.} is the file extension.