Brought to you by molecularsciences.org.
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License.
This publication may not be redistributed without this notice.

Renaming Files in Directory

Suppose you have 2000 photos in a directory and you need to rename them. The files are named as:

IMG_1232.JPG
SP234324.JPG
webdown.JPG
...

We need to rename them as follows:

salzburg_1.jpg
salzburg_2.jpg
...

Here is how:

j=1
s=salzburg_
for f in *.JPG; do
  mv $f $s$j.jpg
  ((j=$j+1))
  echo renaming $f to $s$j.jpg
done

j in is the counter. Line 5 increments j. s is a string. Line 4 uses the mv command renaming each file to the desired combination of text and number. Line 6 prints a message on the command line. Note that in line 3, we only loop through files ending in .JPG.

To specify name from commandline:

j=1
s=$1
for f in *.JPG; do
  mv $f $s$j.jpg
  ((j=$j+1))
  echo renaming $f to $s$j.jpg
done

To run

$ ./rename salzburg_

The commandline is passed into $@ array where $0 is the command followed by first argument $1, then second argument $2, and so on.