Quick Tip: How to Batch Rename in Linux

Have you ever needed to rename a bunch of files and directories recursively in Linux? If so, then a combination of the find and rename commands is your answer. Let me show you how.

Here’s a basic one-line command you can type into a terminal to find and rename all files and directories from your current directory. This example will replace all spaces with a single underscore for each occurence:

 find . -depth -execdir rename 's/ +/_/g' '{}' \;
findCommand to search for files
.Path to perform search. In this case, it's the current directory
-depthThis will process the directory's contents first.
-execdirThe following command is run from the subdirectory containing the matched file. This is a more secure method than using -exec.
renameCommand to rename file/directory
's/ +/_/g'Substitution pattern which follows: 's/pattern/replacement/'. The pattern is a Perl regular expression. In this example, the pattern is a space and we are replacing it with an underscore. The + sign that follows the space is part of the patten and indicates unlimited allowed; one required ("at least one"). Therefore, this will match one or more spaces and replace it with a single underscore. The g means 'global', which instructs rename to match and replace all occurrences.
'{}'The curly braces are part of the find command. This token is replaced with the matched file to be used by the target of the -execdir arguments. The single quotes are required to protect them from interpretation as shell script punctuation.
\;Terminates -execdir. The backslash provides similar protection for the semicolon, though single quotes would also work.

To test your command first, add the -n option to rename as such:

 find . -depth -execdir rename -n 's/ +/_/g' '{}' \;

And that’s it! With this basic knowledge, you can experiment with what files to search for and what patterns to match.

For more information on these various commands, here are some quick links:

MANPAGE: find
MANPAGE: rename
WEBSITE: regular expressions
BOOK: Mastering Regular Expressions by Jeffrey E.F. Friedl