Wednesday, January 19, 2011

How do I rename multiple files efficiently using only the bash shell?

2010-09-10 Fri 17:36

As a concrete example, let us consider the problem that we often have uploading pictures to certain sites (e.g. ebay). The photos from our camera all have .JPG extension. However, when we attempt to locate those pictures from some web sites, no photos are found. This is because something in the chain of events only lower case extensions, such as .jpg, are allowed.

The task is to change all files in a directory (e.g. /DATA01/Pictures/EBAY/2010-09-10) from upper case (.JPG) to lower case (.jpg) extensions.

cd /DATA01/Pictures/EBAY/2010-09-10
for i in *.JPG; do mv "$i" "${i/.JPG}".jpg; done


If the task is a bit more complex will do well to use another standard Unix tool with regular expression capability (such as sed). For example, if we have files with a date in the name (e.g. 20101210) and want to change the date (e.g. to 20110119), then here is solution.

for i in *20101210*; do j=`echo $i | sed s/20101210/20110119/`; mv $i $j; done

Still simple.

No comments:

Post a Comment