Batch renaming files
By bruno combal on Thursday, December 11 2008, 18:27 - Permalink
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!