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)
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 digitsIn case N
is not a priori fixed:
for f in foo[0-9]*; do
mv "$f" "$(printf 'foo%05d' "${f#foo}")"
done
I had a more complex case where the file names had a postfix as well as a prefix. I also needed to perform a subtraction on the number from the filename.
For example, I wanted foo56.png
to become foo00000055.png
.
I hope this helps if you're doing something more complex.
#!/bin/bash
prefix="foo"
postfix=".png"
targetDir="../newframes"
paddingLength=8
for file in ${prefix}[0-9]*${postfix}; do
# strip the prefix off the file name
postfile=${file#$prefix}
# strip the postfix off the file name
number=${postfile%$postfix}
# subtract 1 from the resulting number
i=$((number-1))
# copy to a new name with padded zeros in a new folder
cp ${file} "$targetDir"/$(printf $prefix%0${paddingLength}d$postfix $i)
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With