Using multiple capturing groups in regex substitution

Started by lei, March 22, 2024, 10:41:33 PM

Previous topic - Next topic

lei

Dear Experts,

I stumbled upon an interesting usage in the forum:

exiftool -filename -if "${filename;m/(\d{8}_\d{6})/;$_=$1} ne $DateTimeOriginal" -d "%Y%m%d_%H%M%S" temp

Here, instead of using the normal s/// form, a regex match is utilized for replacement. I find this method sometimes more concise, especially when extracting specific segments of text. Out of curiosity, I tried it myself and found that the assignment part ($_=$1) only works with one capturing group; using more than one results in an error. I'm curious to know why this limitation exists and how one can work with multiple capturing groups in this syntax.

Thanks in advance!

Phil Harvey

#1
You can use multiple capture groups, but they need to be quoted, like this:

-if "${filename;m/(\d{8})_(\d{6})/;$_=qq($1 $2)}"

You can't use single quotes here because variables are interpolated in single quotes, so  use the "qq" double quoting.  Perl allows you to quote things in many different ways.

- Phil

Edit: I just noticed there was only one capture in the example, so I added a couple more brackets.
...where DIR is the name of a directory/folder containing the images.  On Mac/Linux/PowerShell, use single quotes (') instead of double quotes (") around arguments containing a dollar sign ($).

lei

Phil,

That's fantastic! It makes this approach even more useful. Actually, it was already useful; I just wasn't aware of it. The main issue is that I'm not familiar with Perl, so I couldn't come up with such a usage on my own. Looks like I'll need to spend some time learning Perl. As always, I appreciate it.