0

I have a directory containing a large number of image files, some of which are in subdirectories. I need to rename all image files matching *.png, *.jpg, *.jpeg, *.bmp, *.gif using a simple pattern for renaming:

  • the same prefix for all files;
  • a number with padding zeros and printed as hex string.

My goal is to assign a unique name to all image files, independently of their extension, so that I can then convert them to the same image format without the risk of overwriting those files with the same names.

I was writing a script in order to perform the above procedure (for directory listing, I was inspired by the code snippet of this answer).

for root, dirs, filenames in os.walk(path):
    for filename in filenames:
        if filename.endswith((".jpeg", ".jpg", ".png", ".gif", ".bmp")):
            # rename file

I was wondering if there was any bash or powershell command in order to perform the above procedure.

1 Answer 1

1

I'm most fluent in Bash, but I'm sure you could do the same thing in Power Shell. I'm assuming that you are going to convert to .jpg format and store all the files in a ./output/ directory. My script would look like this:

j=0;
for i in `find . -type f \( -iname *.jpg -o -iname *.jpeg -o -iname *.png -o -iname *.gif -o -iname *.bmp \)`
do
    j=$(($j+1))
    convert $i output/`printf "%06X" $j`.jpg
done

This script will start a counter '$j' from 0. Then it finds all files that are of type file (rather than directories or symlinks or other such things) and match your specified extensions in a case insensitive manner. The ( ) groups a series of items that are each joined together with a -o OR specifier for the find command.

We use a for loop to go over all the found files noting them with $i.

Inside the loop, I increment the counter $j.

Then I convert the filename as I found it to .jpg and output into the ./output/ directory.

The hex numbered filename is 0 padded out to six digits using a printf command.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .