Using the commandline editor “sed” for batch renaming of files

Given a set of files, that all end with “.png.jpg”. We want to remove the “.png” from the filename. This can be done using the linux shell pipes and the commandline editor “sed”.

Examine this command: ls * | sed ‘s/\(.*\)png\.\(.*jpg\)/mv & \1\2/’ | sh

The interesting part here is of course sed ‘s/\(.*\)png\.\(.*jpg\)/mv & \1\2/’. The general syntax is “sed ‘s/patternToSubstitue/SubstituteBy/'”.

  • s means “substitute”
  • \(.*\)png\.\(.*jpg\) This splits the given string into a segment of arbitrary content \(.*\), another segment containing the fixed string “png.” and a third segment \(.*jpg\) consisting of a string with arbitrary content ending with “jpg”. The first and third part are dynamically created, so sed allows to reference them using \1 and \2
  • mv & \1\2 This part constructs a command that can be executed by the shell. The “&” references the original string passed into sed, the parts \1 and \2 are generated above and concatenated.

The result of this command is, that the substring “png.” is removed from all filenames in the current directory. Files that don’t match this pattern are not changed, because the mv command gets the same name as source and target file.