A Linux shell script to rename files with a counter and copy them

As a brief note today, I was recently looking for all Messages/iMessage files that are stored on my Mac, and I used this shell script to copy all of those files — many of which have the same name — into a directory named tmpdir, giving them all new names during the copy process:

# WARNING: back up your files before running this script.
#          if something is wrong, you may lose them all.
count=1
for i in `cat myfiles`
do
    fname=`basename $i`
    cp $i tmpdir/${count}-${fname}
    count=`expr $count + 1`
done

The way this works is that I have a file named myfiles that I created with a find command, and it contains a bunch of entries like this:

foo/bar/baz/filename.jpg
foo/baz/filename.jpg

When the shell script runs, it reads one line at a time from that file, gets the basename (filename) from that line, prepends that name with a counter, then copies the original file to the directory named tmpdir, giving it the new name, so the new filenames will be like this:

1-filename.jpg
2-filename.jpg
3-filename.jpg

I did this to copy all of the images I have under the Messages cache folder on my Mac. A friend accidentally deleted our text message stream, and I was able to recover 350+ images with this script.

You can also use it to copy iTunes music files, where it’s possible that many music files (MP3, M4A, etc.) will have the same filename.

(If you’re working with filenames that have spaces in them, you’ll need to set the IFS variable, as I show in this How to process every line in a text file with a shell script tutorial.)