Skip to content

Instantly share code, notes, and snippets.

@kafene
Last active August 29, 2015 14:02
Show Gist options
  • Save kafene/4aa95225d2fe8262784e to your computer and use it in GitHub Desktop.
Save kafene/4aa95225d2fe8262784e to your computer and use it in GitHub Desktop.
Finding and renaming all images with bash

Here's the use case:

I have an exported website that has images deeply nested throughout it in various folders. I want to find all of them, and copy them into a single directory. I don't care about the filenames so for the sake of both dedupliacting the results and making sure no filename collisions occur, I want to name the resulting images $(sha1sum $image).jpg.

So I wrote a small script to do this and I felt like sharing:

shopt -s globstar # Enable `**` for globbing
shopt -s extglob # Enable extended glob matching
shopt -s nocaseglob # Enable case-insensitive globbing
mkdir -p out

for img in ./**/@(*.jpg|*.gif|*.jpeg|*.png); do
    sha="$(sha1sum "$img")"
    sum="${sha%%" "*}"
    file="${sha##*" "}"
    bn="$(basename "$file")"
    ext="${bn##*.}"
    out="./out/$sum.$ext"
    echo "moving $file to $out"
    mv "$file" "$out"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment