One – liner to batch rename files with regex-remove part of the filename

Don’t read this post. It’s only for me so that I don’t forget it ūüėČ

After a long fight with bash, find, sed, … Here is the one – liner:

for i in $(find -E . -regex '(.*[a-zA-Z]{3}[0-9]{3}[a-zA-Z]{3}_[0-9]{9})(\.[0-9])(\.[jJ][pP]([eE])*[gG])') ; do mv -v $i $(echo $i | sed -E 's/(.*[a-zA-Z]{3}[0-9]{3}[a-zA-Z]{3}_[0-9]{9})(\.[0-9])(\.[jJ][pP]([eE])*[gG])/\1\3/') ; done

Given a set of JPEG files, which contained duplicates with .1¬†thrown-in before the final dot and the ending of the filename, replacing the original with the newer ones (those with .1‘s) seemed like a trivial task‚Ķ until I tried to actually do this. In the end it came to using “modern regex” with matching groups and refer to those groups I wanted to retain. These are \1¬†and \3¬†concatenated in the \1\3¬†part of the sed¬†replace pattern. Group \2¬†(the .1) didn’t make it there.


This entry was posted in bash, Coding and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s