Renumbering a series of files

I couldn’t tell you the number of times I’ve gone to run a code to process a series of images or velocity fields only to find that the file name and numbering sequence is not compatible with the particular code I am trying to run (e.g. file names image_00001.jpg to image_100.jpg when program expects image_001.jpg to image_100.jpg) or in the case of particle image velocimetry if you need to convert double shutter to single shutter images and subsequently split images (e.g. image_0001.b16 to image_0001.b16 and image_0002.b16) while maintaining a continuous file number sequence.

Fortunately in OS X or Linux this can easily be accomplished from a terminal using basic bash scripting to automate the otherwise tedious process of renaming files. For instance if you wanted to create a symbolic link to a series of 4 digit images you can loop over this sequence of images using a for loop and use the print command to create the corresponding 4 digit image number string for each image as follows:

for ((i=1; i<=100; i++));
do j=$(printf "%04d" $i);
echo $j;
ln -s ../../RAWDATA/cam1/set01/cam1_"$j".b16 C1_"$j".b16;
done;

Changing a 4 to a 5 digit sequence number is as simple as looping through the sequence and moving the original file name to a new name of your choice, as shown:

for ((i=1; i<=100; i++));
do j=$(printf "%04d" $i);
mv image_"$j".png image_0"$j".png;
done;

note moving files in this was must be done with care as a simple error in the script can erase or overwrite your data. I recommend replacing commands like mv or rm with ls or cp on a first pass in order to test that the number created by the script is what you require.

As mentioned above if you want to replace a data sequence that consists of two parts with a single sequence (e.g. say velocity_0001_A.nc and velocity_0001_B.nc to velocity_0001.nc and velocity_0002.nc) the following script could be used:

for ((i=1; i<=19; i=i+2));
do j=$(printf "%04d" $i);
let k=i+1;
l=$(printf "%04d" $k);
mv velocity_"$j"_A.nc velocity_"$j".nc;
mv velocity_"$j"_B.nc velocity_"$l".nc;
done;

Of course this is only the tip of the iceberg when it comes to bash scripting, which can be used for anything from mining text files for specific phrases to running through a series of files and replacing all occurrences of 01 with 02. I guess that’s an entry for another day.

Leave a Reply

Your email address will not be published. Required fields are marked *