Search code examples
bashrenamebatch-processing

Batch rename files by inserting a quote before the last character of a regex pattern


01 - The situation

Let's say I have hundreds of files like these: (don't care about the file type)

Steven Scott - Stevens Dinner With Sandy.txt
Matt Lang - Matts First Song.txt
Martin Julien - Martins First Trip to Paris.txt

I want to batch rename them to get this output:

Steven Scott - Steven's Dinner With Sandy.txt
Matt Lang - Matt's First Song.txt
Martin Julien - Martin's First Trip to Paris.txt

02 - What i did

I first went to "regexr.com" to write my command. I've matched my pattern with this expression: (( - )(\w+))(?=(s))

Here's the screenshot Perfect match I need that excludes the "s".

The substitution seems very simple to me:

$1'

And still on "regexr.com", I got what I wanted:

Screenshot #2: Good result

Finally I executed the command into a test folder, which once again seems very basic.

rename -vf "s/(( - )(\w+))(?=(s))/$1'/gi" *

This is where I stop understanding what happened... Here's the output:

Martin Julien's First Trip to Paris.txt Matt Lang's First Song.txt Steven Scott's Dinner With Sandy.txt

Can anyone tell me what happened or if I made a mistake?

Thanks for your insights... Martin


Solution

  • This simplified regex is more readable :

    rename -v -f "s/( - \w+)(?=s)/\$1'/gi" *