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

As a quick note, I used this shell script to copy many files with the same name into a directory named tmpdir, giving them all new names during the copy process:

for i in `cat myfiles`
    fname=`basename $i`
    cp $i tmpdir/${count}-${fname}
    count=`expr $count + 1`

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:


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:


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.)

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.