Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zero pad numbers in file names in Bash?

Tags:

bash

rename

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)
like image 700
Trastle Avatar asked Sep 11 '08 03:09

Trastle


3 Answers

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
like image 57
KARASZI István Avatar answered Oct 13 '22 20:10

KARASZI István


In case N is not a priori fixed:

for f in foo[0-9]*; do
  mv "$f" "$(printf 'foo%05d' "${f#foo}")"
done
like image 40
Chris Conway Avatar answered Oct 13 '22 21:10

Chris Conway


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
like image 21
Michael Baltaks Avatar answered Oct 13 '22 20:10

Michael Baltaks