17.22 Rename Files

20200915

To rename a collection of files, perhaps all files in a directory, the rename command is useful. If can perform complex pattern based renaming operations. Through this chapter, as well as in other chapters, we have used this command. The essential syntax is:

$ rename [-n|-v] 's|<regexp>|<replacement>|' *

Note the use of -n (--nono) will not rename any files but will show what the command would do if it we allowed to do so. This is always good practise in the first instance. Once the proposed renaming looks right, drop the -n.

The -v (--verbose) is our traditional verbose option to show what is renamed. This is very useful in case the renaming is not what you wanted. Copy the trace of the renaming into a file, and edit it it rename them back to the original!

The quoted pattern could be s as it is above to substitute (i.e., replace a pattern with some other string/pattern) or y to transliterate (i.e., convert one set of characters to another).

Typical examples include the following, and running all the commands will result is a standard naming scheme.

rename -v 'y|A-Z|a-z|' *                 # Convert to lowercase.
rename -v 's| +|_|g' *                   # Replace one or more spaces with underscore.
rename -v 's|_\.|.|' *                   # Remove underscore before a period.
rename -v 's|[~\-&:\(\)\[\]]|_|g' *      # Replace special characters with underscore.
rename -v 's|_+|_|g' *                   # Remove multiple underscores.
rename -v 's|&|and|g' *                  # Expand ampersand.

Common strings can be removed if desired:

rename -v 's|_fred_watson||' *

Te remove special characters rather than replacing them with underscore:

rename -v "s|['\(\)\[\]\`,\!]||g" *

To replace backup numbering with a version number like 20201129_paper163.pdf.~2~ to 20201129_paper163_2.pdf:

rename -v 's|.pdf. ([0-9]+)~|_$1.pdf|' *     # Replace backup with number.

Other examples are found in Sections 17.19, 17.24, and 9.1.



Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0