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'ssprintf
, and%05d
will pad to five digits
In case N
is not a priori fixed:
for f in foo[0-9]*; do
mv "$f" "$(printf 'foo%05d' "${f#foo}")"
done