user19594390
user19594390

Reputation:

Perl regex capture groups

I use perl regex capture groups to replace the pattern of a large number of files.

File example 1:

title="alpha" lorem ipsum lorem ipsum name="beta"

File example 2:

title="omega" Morbi posuere metus purus name="delta"

for

title="beta" lorem ipsum lorem ipsum
title="delta" Morbi posuere metus purus

using

find . -type f -exec perl -pi -w -e 's/title="(?'one'.*?)"(?'three'.*?)name="(?'two'.*?)"/title="\g{two}"\g{three}/g;' \{\} \;

(Note that (1) attribute values of title and name are unknown variables and (2) the content between title="alpha" and name="beta" differs. )

I am still learning perl regex. What am I doing wrong?

Upvotes: 1

Views: 327

Answers (1)

Erwin
Erwin

Reputation: 954

Your challenge is the shell quoting, but also the user of named capture groups. I'm not quite clear on whether you can use those the way you do, in the substitution.

This works to accomplish your task, as I understand it:

find . -type f -exec perl -pi -w -e 's/title="(.*?)"(.*?)name="(.*?)"/title="$3"$2/g;' \{\} \;

For instance:

$ cat file1
title="alpha" lorem ipsum lorem ipsum name="beta"

$ cat file2
title="omega" Morbi posuere metus purus name="delta"

Run the above line, and then:

$ cat file1
title="beta" lorem ipsum lorem ipsum

$ cat file2
title="delta" Morbi posuere metus purus

Hope that helps.

Upvotes: 1

Related Questions