From LQWiki
Jump to: navigation, search

Different rename programs come with different linux distributions. In addition, there is a standard library function called rename().

Rename (util-linux program)

rename is a program that renames sets of files using simple substitutions. It comes with the util-linux package in the Red Hat distribution. The usage is:

$ rename fromtext totext filelist ...

For each file in filelist, rename subtsitutes totext for every instance of fromtext in creating the new name of the file. This is equivalent to the bash command:

$ for f in filelist ... ; do mv $f ${f/fromtext/totext} ; done

Most (all?) Linux distributions incorporate this version from the [util-linux] project. As it is currently a Perl program, the above syntax (no longer?) works, and the Perl version (below) is what you get.

Rename (perl program)

rename is a program that renames files using perl regular expessions. It comes with the perl package in the Debian distribution. rename can be really useful when renaming huge amounts of files. The first argument is a perl regular expression that tells us how to match things, and the other is matching files. For example:

$ rename 's/\.mpeg/\.mpg/' *.mpeg

This would rename all files that have ".mpeg" in it's name to files having ".mpg" instead: Example:

$ ls
A.mpeg  B.mpeg  C.mpeg
$ rename 's/\.mpeg/\.mpg/' *.mpeg
$ ls
A.mpg  B.mpg  C.mpg

More examples, we want all files to be prefixed with the string "boring".

$ rename 's/^/boring/' *

Further, we would like to uppercase the first character in each filename.

$ rename 's/^\w/\U$&/g' *

The crucial part here is understanding regular expressions. man perlre might help you out here.

rename() (library function)

rename() is also an ANSI C library function available on any system. The prototype is:

int rename(const char *oldname, const char *newname);

rename() returns zero on success or non-zero on error.

See also

  • File commands
  • mv - For simple 'one file' renames
  • mmv - Another renaming program
  • Bash tips - Another way to rename files using only bash, albeit with simple substitutions, not regex.
  • BatRen - Batch file renaming tool

External links