How to zero pad numbers in file names in Bash?


Question

What is the best way, using Bash, to rename files in the form:

(foo1, foo2, ..., foo1300, ..., fooN)

With zero-padded file names:

(foo00001, foo00002, ..., foo01300, ..., fooN)
1
45
10/28/2017 7:16:37 PM

Accepted Answer

In case N is not a priori fixed:

 for f in foo[0-9]*; do mv $f `printf foo%05d ${f#foo}`; done
27
9/11/2008 3:47:46 AM

It's not pure bash, but much easier with the rename command:

rename 's/\d+/sprintf("%05d",$&)/e' foo*

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon