LinuxCommandLibrary

file-rename

Rename files

TLDR

Rename files using a Perl Common Regular Expression (substitute 'foo' with 'bar' wherever found)

$ rename ['s/foo/bar/'] [*]
copy

Dry-run - display which renames would occur without performing them
$ rename [[-n|--nono]] ['s/foo/bar/'] [*]
copy

Force renaming even if the operation would remove existing destination files
$ rename [[-f|--force]] ['s/foo/bar/'] [*]
copy

Convert filenames to lower case (use -f in case-insensitive filesystems to prevent "already exists" errors)
$ rename 'y/A-Z/a-z/' [*]
copy

Replace whitespace with underscores
$ rename 's/\s+/_/g' [*]
copy

SYNOPSIS

rename [options] expression files

PARAMETERS

-v
    Verbose mode: show the changes being made.

-n
    No-op mode: don't actually rename files, just print what would happen.

-f
    Force: overwrite existing files. Use with caution.

-e expression
    Perl expression to execute. This can be used instead of the 'expression' argument.

DESCRIPTION

The file-rename command, often shortened to rename, provides a powerful way to rename multiple files simultaneously using Perl regular expressions. It iterates through the specified files and applies a substitution based on the provided expression. This enables complex renaming operations, such as changing file extensions, replacing patterns, or modifying filenames based on their content. It's a powerful tool for batch file manipulation, offering more flexibility than simple wildcard-based renaming.

It's crucial to understand Perl regular expressions to effectively use rename. Without a good understanding, it's easy to inadvertently rename files incorrectly. The command typically uses the syntax `s/old/new/`, similar to Perl's substitution operator, to define the renaming rule. Before committing to the changes, it's recommended to use the -n (no-op) option to preview the intended renaming actions, preventing accidental data loss or corruption.

CAVEATS

Careless use of rename can lead to data loss. Always test with the -n option before making changes.

EXAMPLES

Rename all *.txt files to *.bak:
rename 's/\.txt$/\.bak/' *.txt

Remove all spaces from filenames:
rename 's/ //g' *

Convert filenames to lowercase:
rename 'y/A-Z/a-z/' *

PERL EXPRESSION BASICS

The core of rename lies in Perl regular expressions. The most common structure is s/old/new/, where 's' signifies substitution, 'old' is the regular expression to find, and 'new' is the replacement string. Flags can be added after the final slash (e.g., 'g' for global replacement). Understanding quantifiers (*, +, ?, {}, etc.) and character classes ([a-z], [0-9], \d, \w, etc.) is essential.

SEE ALSO

mv(1), find(1), sed(1)

Copied to clipboard