Codemonkey
Codemonkey

Reputation: 4807

Is it possible to repeat a match in a grep regexp?

I am using this:

grep '\s[A-Z]+\s[A-Z]+\s' file.txt -Po

Which will match

 ABC DE
 AB AB
 DEF GHIFOO

etc

What I want to do is something like

grep '\s([A-Z]+)\s%1\s' file.txt -Po

to only match

 AB AB
 BC BC
 DDD DDD

etc.

I can't work out if it's even possible, let alone how. Is it?

Thanks

Upvotes: 1

Views: 39

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The first captured group should be specified as \1 not as %1:

Sample file.txt:

AA AB
AB AB
BC BC
DDD DDD
NN WN

Consider the updated regex patten:

grep -Po '\b([A-Z]+)\s\1\s*' file.txt

The output:

AB AB
BC BC
DDD DDD

Bonus approach for opposite action:

grep -Po '\b([A-Z]+)\s(?!\1)[A-Z]+\s*' file.txt

The output:

AA AB
NN WN

Upvotes: 1

Related Questions