Bash - bulk image processing
Published - 2020-09-11


This week I found myself staring at a directory of images that were completely unusable by the application that I was working with. These are images of playing cards and the application expects something like c1.png for Ace of Clubs, s12.png for Queen of Spades, etc. But what we were given looked like CLUB-1.svg and SPADE-12-QUEEN.svg.

So what this means is I need to convert all of these .svg files to .png and rename the new .pngs so they align with what the application expects. Obviously, I could rename these one by one then open each in inkscape and export as .png, but where's the fun in that? So I wrote a script to do it for me.

My first step is to list all of the .svgs in my current directory and pipe that output to awk so I can print an inkscape command...

ls -l *.svg* | awk '{print("inkscape -o "$NF " " $NF)}'

This gives me a long list of commands that look like this...

inkscape -o CLUB-1.svg CLUB-1.svg
inkscape -o SPADE-12-QUEEN.svg SPADE-12-QUEEN.svg

Looks good. Now I need to replace the .svg in the first instance of the filename with .png, and CLUB, HEART, DIAMOND and SPADE with c, h, d and s respectively. (the first instance of the filename designates the name and type of file that inkscape will output). I can do this by piping this output to a sed command...

# continuation of previous command
| sed 's/.svg/.png/; s/CLUB/c/; s/HEART/h/; s/DIAMOND/d/; s/SPADE/s/'

...and now I have something like...

inkscape -o c-1.png CLUB-1.svg
inkscape -o s-12-QUEEN.png SPADE-12-QUEEN.svg

Getting close. Now to remove -JACK, -QUEEN and -KING from the end and convert c-1 to c1, s-12 to s12, etc...

| sed 's/-JACK//; s/-QUEEN//; s/-KING//; s/-//2'

This gives me...

inkscape -o c1.png CLUB-1.svg
inkscape -o s12.png SPADE-12-QUEEN.svg

Now I just need to output this list of commands to a file and run it. This is what it looks like when it's all put together.

touch &&
ls -l *.svg* | awk '{print("inkscape "$NF " " $NF)}' \
| sed 's/.svg/.png/' \
| sed 's/CLUB/c/' \
| sed 's/DIAMOND/d/' \
| sed 's/HEART/h/' \
| sed 's/SPADE/s/' \
| sed 's/-JACK//' \
| sed 's/-QUEEN//' \
| sed 's/-KING//' \
| sed 's/-//2' > &&
sh &&
rm &&
rm *.svg &&
echo "Processing complete."

The point could be made that this was kind of a waste of effort since it's not something I'm ever likely to use again, but it was a fun exercise and that's almost always a good thing.