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 tyhe 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).

Here’s some typical use cases:

Replace all spaces with an underscore:

rename -n 's/ /_/g' *

Replace a string of underscore with a single underscore:

rename -n 's/__*/_/g' *

Convert all filenames to lowercase only filenames:

rename -n 'y/A-Z/a-z/' *

Some more special purpose examples:

Rename backup versions using n style to numeric versions.

rename -n 's/.pdf.&nbsp;([0-9]+)~/_$1.pdf/' *

This will rename 20201129_paper163.pdf.&nbsp;2&nbsp; as 20201129_paper163_2.pdf.

Remove a redundant final underscore.

rename -n 's/_\././' *

This will rename 20201129_paper163_.pdf as 20201129_paper163.pdf.

Replace various symbols with underscore.

rename -n 's/[&:\(\)\[\]]/_/g' *

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