user1583209 user1583209 - 9 months ago 44
Linux Question

Add leading zeros twice in filename

I have file names (from image tiles) consisting of two numbers separated by an underscore, e.g.


How can I (in linux) add leading zeros to both of these numbers? What I want is the file names as


Answer Source

With perl based rename command

$ touch 142_27.jpg 7_39.jpg 1_120.jpg
$ rename -n 's/\d+/sprintf "%03d", $&/ge' *.jpg
rename(1_120.jpg, 001_120.jpg)
rename(142_27.jpg, 142_027.jpg)
rename(7_39.jpg, 007_039.jpg)

The -n option is for dry run, remove it for actual renaming

If perl based rename command is not available:

$ for f in *.jpg; do echo mv "$f" "$(echo "$f" | perl -pe 's/\d+/sprintf "%03d", $&/ge')"; done
mv 1_120.jpg 001_120.jpg
mv 142_27.jpg 142_027.jpg
mv 7_39.jpg 007_039.jpg

Change echo mv to just mv once dry run seems okay