This one is a classic in the use of shell scripts: batch renaming (image) files. You can find solutions on how to batch rename files on stackoverflow (e.g., here and here).

The mentioned examples employ the rather elegant bash parameter expansion feature to match and replace patterns instead of using bulky awk or sed constructs. Although the scripts solved the (specialized) problem the asker seeked to solve, I found the syntax of the parameter expansion complex to understand at first sight. You can find generalized explanation approaches like this, but I hate this man pages kind of explanation.

So here you find a convenient graphical explanation with an example of what the parameter expansion actually does:

By the way, the script in the whole works like this: in the for loop it lists files ending with ” 2.CR2″ and in the mv command, the parameter expansion looks also for ” 2.CR2″ and replaces it with “.CR2”.

Here is the code snippet for copy and paste:
for i in *" 2.CR2" ; do mv "$i" "${i/ 2.CR2/.CR2}" ; done

Before you move the files, you will want to use this command to list you which files will be affected:
for i in *" 2.CR2" ; do echo "$i" ; done

Published by Johannes Luderschmidt

About this blog