Programming and accessibility tips

from the Cynthia Network

Shell »

Use a shell command to pad numbered filenames with 0s

Applications that browse files and folders (such as file managers and file editors) allow for sorting the files in a folder based on the filename. Strings of alphabetic characters are typically sorted in alphabetical order. Strings of numerical characters may be sorted as if they were numbers (with the string '2' coming before the string '11') but some applications may sort numerical strings using alphabetic order. In alphabetical order, the string '11' comes before '2' in the same way that the string 'aa' comes before the string 'b'. When numerical order is essential (for example, if files are named based on their page numbers from a scanned book) then it may be necessary to pad the filenames with 0s to ensure the desired ordering. For example, if files are named 1.jpg, 2.jpg, ..., 10.jpg then the file 10.jpg may appear before the file 2.jpg in a ordered list. If we rename the filenames 1.jpg, ..., 9.jpg to have a leading 0 (01.jpg, ..., 09.jpg) then the filenames will be sorted in numerical order under either ordering techniques.

Since we do not know how many files may be in a folder, we would like an automatic method for renaming the files in the appropriate way. Suppose that we have a folder of .jpg files. We can exceute the following command from the shell prompt to rname the files:

ext='jpg'; for i in *.$ext; do num=`expr match "$i" '\([0-9]\+\).*'`; padded=`printf "%03d" $num`; mv -v "$i" "${i/$num/$padded}"; done

The above command has two components:

  1. ext='jpg';
    ext is a variable that stores the extension of the files that we want to rename.
  2. for i in *.$ext; do num=`expr match "$i" '\([0-9]\+\).*'`; padded=`printf "%03d" $num`; mv -v "$i" "${i/$num/$padded}"; done
    This part of the command iterates through all of the files with the desired extension and concatenates a 0 to the beginning of the filename.

Computer science help



By Bill Hollingsworth
© 2016 by Cynsight, LLC.
Cynthia™ is a trademark of Cynsight, LLC.