Bulk Renaming Files in Linux

You have a heap of files names in a particular way and you want to have them named in another way. The rename function is your answer,

rename \[ -v \] \[ -n \] [ -f ] perlexpr [ files ]

The trick here is the perlexpr part. This is a perl regual expression – or simply a search and replace string of the format

's/find/replace/g'

Example

rename all occurrances of “htm” with “html”.

rename 's/htm/html/g' *

Remember to escape any special characters with a backslash.

rename 's/\.htm/\.html/ g' *.htm

Example

Suppose you has a set of a TV series named in the following format;

name.of.series.S01E02.title.of.episode.avi

and wanted the format

02 - title of episode.avi

You could run the following commands

rename -v 's/\./ /g' *
rename -v 's/ avi/\.avi/g' *
rename -v 's/name of series S01E(\d{2}) /$1 - /' *.avi
rename -v 's/name of series S01E(\d{2})\./$1\./' *.avi

Which does the following

  • Replace all periods with spaces
  • Replace the period before the extension (avi)
  • Remove the series name from the start and add a hyphen for cases where there is a title
  • Remove the series name from the start where there is not title

Example

Rename all files of the format “Series.Title.S00E01.Other.Text.avi” to “01.avi”

rename -v 's/.*E(\d{2}).*\.avi/$1\.avi/g' *

Leave a comment

Your email address will not be published. Required fields are marked *