Rename files in Bash with Regular expressions
- April 7, 2013
Sometimes it’s necessary to rename files in Bash following some patterns. Doing this task manually could be exhausting and time consuming if you have a thousand files to rename.
For this reason, I use rename command:
Debug and preview:
$ rename'REGULAR EXPRESSION' files -n
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: [code lang='bash'] $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.
