bashimageterminalrenamesips

Terminal: Use image information from sips for renaming files


The command sips has a great option to read information from files. The following command loops through all images and shows information on the width or height:

for i in *.jpg; do sips -g pixelWidth $i;done

for i in *.jpg; do sips -g pixelHeight $i;done 

Now I would like to read this information and use it with mv to rename the images like so:

image-widthxheight.jpg

image-1600x900.jpg

The final thing I want accomplish is, to use sips to resize images and write the new information directly into the filename.

Has anybody an idea, how I can extract the information from width and height and use it together with mv?


Solution

  • I found it out myself. It's a nice bash script now. Maybe not so elegant, but it works – It's also available as a gist on GitHub.

    NEW VERSION THANKS TO THE ADVICE – SEE COMMENTS

    #!/bin/bash
    #
    #   1. This script copies all *.jpg-files to a new folder
    #   2. Jumps into folder and resizes all files with sips
    #   3. Renames all files and uses information from sips
    #
    folder="resized_and_renamed"
    
    mkdir -p "$folder"
    
    cp *.jpg "$folder"
    
    cd "$folder"
    
    # RESIZE ALL IMAGES TO MAXIMUM WIDTH/HEIGHT OF 360
    sips -Z 360 *.jpg
    
    # RENAME FILES WITH INFORMATION FROM SIPS
    for i in *.jpg
      do
        pixelWidth=$(sips -g pixelWidth "$i" | awk '/pixelWidth:/{print $2}')
        pixelHeight=$(sips -g pixelHeight "$i" | awk '/pixelHeight:/{print $2}')
        # REMOVE EXTENSION
        filename=${i%.jpg}
        # NOW RENAME
        mv $i ${filename##*/}-${pixelWidth}x${pixelHeight}.jpg
      done