Rename – How to Mass Rename Files with Ill-Formed Numbering

rename

I've got bunch of files with ill-formed numbering:

prefix-#.ext       | for files with number 1-9
prefix-##.ext      | for files with number 10-99
prefix-###.ext     | for files with number 100-999

Due to further processing I need all of their names to be in format: prefix-###.ext. Is there any easy way to do that?

Best Answer

On Debian, Ubuntu and derivatives, you can use the rename Perl script:

rename 's/(?<=-)([0-9]+)/sprintf "%03d", $1/e' prefix-*.ext

Some systems may have this command installed as prename or perl-rename. Note that this is not the rename utility from the util-linux suite which does not provide an easy way to do this.

In zsh, you can use zmv to rename and the l parameter expansion flag to pad with zeroes.

autoload -U zmv
zmv '(prefix-)(*)(.ext)' '$1${(l:3::0:)2}$3'

You can also do this with a plain shell loop. Shells don't have nice string manipulation constructs; one way to pad with zeroes is to add 1000 and strip off the leading 1.

for x in prefix-*.ext; do
  n=${x%.ext}; n=${x##*-}; n=$((n+1000))
  mv "$x" "${x%-*.ext}${n#1}${x##*-}"
done

Another way is to call the printf utility.

for x in prefix-*.ext; do
  n=${x%.ext}; n=${x##*-}
  mv "$x" "${x%-*.ext}$(printf %03d "$n")${x##*-}"
done
Related Question