re: Batch renaming images, including image resolution, with awk VIEW POST


Nice post, Vicky.

You can actually take advantage of a couple of awk features and other shell tools to simplify your one-liner a bit, especially if you're willing to assume that there are no colons or commas in the original filenames. You should also be aware that file will produce additional output if there is an EXIF tag in your JPEG image, which will cause the resolution to no longer be in the 8th field.

IMG_4299.JPG: JPEG image data, Exif standard: [TIFF image data, little-endian, direntries=12, manufacturer=Canon, model=Canon EOS 5D Mark II, orientation=upper-left, xresolution=196, yresolution=204, resolutionunit=2, datetime=2017:04:07 18:27:16], baseline, precision 8, 5616x3744, frames 3

Okay, so AWK gives you a couple of variables for free. You get NR which is the number of records (lines) seen so far, so you don't actually need your a variable. It also gives you NF which is the number of fields. This is useful here because regardless of the output format, the resolution is always in the second to last field. i.e. $(NF-2).

You can use printf to produce what is almost the final filenames (it still has the extra : and , but assuming no colons or commas in the original filename, you can just use tr -d :, to delete all the colons and commas.

Putting it all together;

file IMG* | awk '{ printf "%s img_%d_%s.jpg\n",$1,NR,$(NF-2) }' | tr -d :, | xargs -L1 mv

Of course, file produces a pretty different output for other image formats so things will go horribly wrong if some PNGs or other file formats sneak in there.


Great notes! Thanks Vinay!

Yeah, definitely not a copy-paste solution, and needs adjustment for different formats and data output from file. Thanks for telling me about NR and tr -d!

Code of Conduct Report abuse