GP SoftwareTwitter
Opus FAQsManualCommandsObjects

Perl substitutions

perl
scripting

#1

I thought I would share my script that allows renaming via regular expression substitution (think perl, sed, vi, vim, etc.). The syntax is pretty trivial:

Old name: pattern
New name: replacement/flags

The /flags portion is optional - these are the standard Ignore Case (i) and Global flags (g).

Because the pattern and replacement are entered real time, you can see the substitutions happening in the preview window as you make changes. This is great for seeing how regular expressions work too.

Why is this useful? Here's my reasoning - you may disagree (and that's OK).

DOpus regular expression renaming requires pattern capturing and matching of the entire filename in the Old name parameter, and then a reassembly of each component in the New name field. This can sometimes be more difficult to do, and certainly more cumbersome when the goal is a simple substitution operation.

For example: to replace the sequence " - " with a "+" in DOpus' RE rename:

Old name: (.*)\s-\s(.*)# -> abc - def - ghi - jklm.txt
New name: \1+\2 -> abc+def+ghi+jklm.txt

We have to ask for the front matter, the stuff we want to cut out, and the back matter. This gets more complicated if we want to deal with a possible leading "- " sequence (note it is missing the initial space):

Old name: (?:^- )?(.*) - (.*)# -> - abc - def - ghi - jklm.txt
New name: \1+\2 -> abc+def+ghi+jklm.txt

So we had to grab an optional initial sequence, more not-so-front matter, the portion to cut, and then the back matter. Whew.

So lets instead solve the problem with simple substitution:

Old name: (^|\s)-\s
New name: +/g

Notice we don't have to try to match the entire filename, just the parts we need to replace. We've asked for either the beginning of the line or a space followed by the rest of the stuff to cut. That's it. The global flag (/g) performs the operation throughout the line.

Perl's internal string interpolation constructs are available too. The following, for example, globally uppercases all first letters:

Old name: \b(\w)
New name: \U\1/g

Adding a + and removing the global flag uppercases all the letters of the first word:

Old name: \b(\w+)
New name: \U\1

And this one reverses the two first words, lowercasing the now first word and uppercasing the now second word:

Old name: \b(\w+)\s(\w+)
New name: \l\2 \U\1

The attached script requires ActivePerl to be installed. Its free. Give it a try.
Perl Substitution.zip (601 Bytes)