How to zero pad numbers in file names in Bash?

It’s not pure bash, but much easier with the Perl version of rename:

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

Where 's/\d+/sprintf("%05d",$&)/e' is the Perl replace regular expression.

  • \d+ will match the first set of numbers (at least one number)
  • sprintf("%05d",$&) will pass the matched numbers to Perl’s sprintf, and %05d will pad to five digits

Leave a Comment