Tuesday, December 20, 2011

Rename files at linux

I recall "mv" while my colleague ask me how to rename lots of files.
Here is the question:
There are many files. How do we modify its extended name? For example, a.log, b.log, c.log...etc.
We need to change extended from "log" to "txt".

The below answer is incorrect:
mv *.log *.txt

"rename" is the correct command for this time. Here is man page of rename
NAME
       rename - renames multiple files

SYNOPSIS
       rename [ -v ] [ -n ] [ -f ] perlexpr [ files ]

DESCRIPTION
       "rename" renames the filenames supplied according to the rule specified
       as the first argument.  The perlexpr argument is a Perl expression
       which is expected to modify the $_ string in Perl for at least some of
       the filenames specified.  If a given filename is not modified by the
       expression, it will not be renamed.  If no filenames are given on the
       command line, filenames will be read via standard input.

       For example, to rename all files matching "*.bak" to strip the
       extension, you might say

               rename 's/\.bak$//' *.bak

       To translate uppercase names to lower, you'd use

               rename 'y/A-Z/a-z/' *


For my case, I can use following command:
 rename 's/\.log$/\.txt/' *.log


No comments: