Rename files in Bash with Regular expresions

Sometimes It’s necessary to rename files following some patterns. Do this task manual is a long task, if you thousand of files. For this reason, I use rename command:

Debug and preview:

$ rename’REGULAR EXPRESSION’ files -n

Execute:

$ rename’REGULAR EXPRESSION’ files

Some of the most common expressions I use are:

Convert filename to lowercase:

$rename ‘y/A-Z/a-z/’ *

Add Prefix to filename:

 

$rename ‘s//text-/’ *.mp3

Remove Suffix:

$rename ‘s/ – text//’ *.mp3

Dynamic Rename

rename ‘s/(.*?)-(.*).mp3/$2-$1.mp3/’ *.mp3

More Information in manual of rename:

$man 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/’ *
OPTIONS
       -v, –verbose
               Verbose: print names of files successfully renamed.
       -n, –no-act
               No Action: show what files would have been renamed.
       -f, –force
               Force: overwrite existing files.
ENVIRONMENT
       No environment variables are used.