Monday, February 7, 2011

Bash script to pad file names

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)
  • The following will do it:

    for i in ((i=1; i<=N; i++)) ; do mv foo$i `printf foo%05d $i` ; done
    

    EDIT: changed to use ((i=1,...)), thanks mweerden!

    mweerden : Instead of using seq I would suggest writing for ((i=1; i<=N; i++)); do etc. Besides being part of bash, this also avoids having to first generate all numbers and then executing the for.
    From dF
  • Here's a quick solution that assumes a fixed length prefix (your "foo") and fixed length padding. If you need more flexibility, maybe this will at least be a helpful starting point.

    #!/bin/bash
    
    # some test data
    files="foo1
    foo2
    foo100
    foo200
    foo9999"
    
    for f in $files; do
        prefix=`echo "$f" | cut -c 1-3`        # chars 1-3 = "foo"
        number=`echo "$f" | cut -c 4-`         # chars 4-end = the number
        printf "%s%04d\n" "$prefix" "$number"
    done
    
    From amrox
  • In case N is not a priori fixed:

     for f in foo[0-9]*; do mv $f `printf foo%05d ${f#foo}`; done
    
  • Pure Bash, no external processes other than 'mv':

    for file in foo*; do
      newnumber='00000'${file#foo}      # get number, pack with zeros
      newnumber=${newnumber:(-5)}       # the last five characters
      mv $file foo$newnumber            # rename
    done
    
    From fgm
  • I had a more complex case, where the file names had a postfix as well as a prefix, and I also needed to perform a subtraction on the number from the filename. So I wanted foo56.png to become foo00000055.png. I hope this helps if you're doing something more complex.

    #!/bin/bash
    for file in foo[0-9]*.png; do
      # strip the prefix ("foo") off the file name
      postfile=${file#foo}
      # strip the postfix (".png") off the file name
      number=${postfile%.png}
      # subtract 1 from the resulting number
      i=$((number-1))
      # copy to a new name in a new folder
      cp ${file} ../newframes/$(printf foo%08d.png $i)
    done
    

0 comments:

Post a Comment