Batch renaming files

Whether you are using linux (bash or shell) or cygwin, renaming a (large) set of files is really easy. Because renaming a file and changing its location is the same thing for linux and cygwin, you’ve got a large set of possibilities.

First example. Say you have 200 files in a directory that must receive a prefix like new_. Here is what you can write from the prompt.

for f in * ; do mv $f new_$f ; done

and ALL files in the current directory have their names starting with new_ now.
The star * tells to consider any file. For each file found, its name is stored in the variable f and the command mv $f new_$f is executed. The $f is replaced by each filename.
Moving the files to another place is trivial. Say you have a directory named source and another named target, you can:

cd source
for f in * ; do mv $f ../target/new_$f ; done
cd ..

(you can use cp instead of mv to copy the original files to another named file).

Second example. Now you want to change the file extension. It comes that bash lets you do some operations on the variables. For example, if f contains a string that ends with .img, say my_image.img, the instruction ${f%.img} would remove the extension .img from the end of the string (more manipulation in future posts). Renaming files ending with .img with .ida would be:

for f in *.img ; do mv $f ${f%.img}.ida ; done

More on files manipulation in future posts!


3 Responses to “Batch renaming files”

  1. 1 Marco 7 June 2010 at 11:24 am

    The rename command can be used too. For example

    rename .txt .csc *.txt

    • 2 bubuitalia 7 June 2010 at 12:49 pm

      @Marco. Actually rename (or ren) is an msdos command (interested readers will find more doc on it at

      My idea in this post was about how to process a large amount of files in a shell script. Renaming files is an example, but of course you can do way more inside the loop (you’ll find more complex examples in more recents posts, see for example “building gtopo 30′”).

      But you are right, for what is strictly about renaming, you don’t need a loop as far as the manipulation is simple. I’ll give more examples about what can be done in a single bash command line.

  1. 1 Creating dummy (empty) files « EO-toolbox Trackback on 11 December 2008 at 9:32 pm

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

December 2008
« Nov   Jan »

%d bloggers like this: