Using linux find and copy to condense photos to a single directory

Recently I was tasked; being the resident computer expert among family and friends; with saving hundreds of photos from a crashed computer. I ended up having to remove the hard drive from the computer, and attach it to my linux box to copy the entire directory structure. Once copied, I had all the files from that computer stored on my linux file server. Being there was no need to give my friend everything that existed on that drive, I wanted to just copy all photos and images that I could find and copy them to a new directory.

Pictures were scattered among many directories on the drive, and I wanted to condense all images into one directory rather than copy some crazy directory structure that already existed. I chose to use the linux find command to search for files. After a quick attempt to find and copy, I discovered a few simple issues that I would need to solve.

  • The files and paths may have spaces in them. Doh!!
  • Being photos, it is quite possible one directory might have DSC0001.JPG, while another directory might also have a different photo named DSC0001.JPG

It took a little experimenting to find and copy files, with spaces, and renaming any files with the same name, as I was condensing many folders of images into a single folder. Obviously, I did not want to overwrite a file with the same name, as I may lose any number of photos that way.

Here then, is my little bash script in case anyone else needs to accomplish a similar task.

 

#!/bin/bash

find ./ -iname '*.jpg' -printf "%f:%h\n" -o -iname '*.gif' -printf "%f:%h\n" | while IFS=":" read NAME PATH
do
   oldFile=$PATH"/"$NAME
   newFile="../my_images/"$NAME

   x=0
   while [ -f "$newFile" ]; do
      x=$(($x+1));
      newFile="../my_images/"$x"_"$NAME;
   done

   /bin/cp -av "$oldFile" "$newFile"
done

Leave a Reply

Your email address will not be published.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*