Find filenames with three digits and add zeros to make five digits

Hello all! I've looked all over the internet and this site and have come up a loss with an easy way to make a bash script to do what I want to do. I have a file with a naming convention as follows:

2012-01-18 string of words here 123.jpg
2012-01-18 string of words here 1234.jpg
2012-01-18 string of words here 12345.jpg

What I am trying to do is search through all my files and folders within a directory and rename all the files so they have a five digit number instead of a three or four digit number with any empty space filled by a zero.

2012-01-18 string of words here 00123.jpg
2012-01-18 string of words here 01234.jpg
2012-01-18 string of words here 12345.jpg

As seen above, some files have three digits, some four, and some five. Is there any easy way to achieve this? I've been using the find command along with rename traversing folder by folder to change all my files into this format. :wall: Any help would be greatly appreciated. :D:b:

Probably lots of ways to do this. You can pipe the output of a find command through this small awk which will generate the mv commands.

find . -type f | awk '{ o = $0; split( $NF, a, "." ); $(NF)=sprintf( "%05d.%s", a[1], a[2] ); printf( "mv \"%s\" \"%s\"\n", o, $0 ); }'

You can then pipe the output through your favorite shell to actually execute the moves (verify that they look good, and no undesired file is being affected. It's generic so it will handle any suffix (.jpg, .png, etc.). It does assume that in the bag of words in the middle, the last word and the number are separated by a space.

1 Like

Awesome agama! That worked beautifully! The files with five digits were ignored as the filename was the same as destination name. I wish that I had gotten into *nix programming much earlier so I would know this stuff better, but now just trying to self teach myself these fun little things. :slight_smile: