How to get the contents of the subgroup matched by a regular expression

Viewed 53

like this: p.txt

abc-111-zzz-022-ffff
abc-222-zzz-033-ffff
abc-333-zzz-044-ffff

I can get the full match ($0 in regex):

[root@ser user]# grep -Po 'abc\-([0-9]+)\-zzz\-([0-9]+)' p.txt
abc-111-zzz-022
abc-222-zzz-033
abc-333-zzz-044

How can I get only subgroup content $1$2 like :

111022
222033
333044

thanks!

1 Answers

grep doesn't allow printing capture groups. Use sed:

sed -E 's/abc-([0-9]+)-zzz-([0-9]+).*/\1\2/' file

111022
222033
333044

Alternatively, if you have pcregrep then use this command to print first 2 capture groups:

pcregrep -o1 -o2 'abc-([0-9]+)-zzz-([0-9]+)' file

111022
222033
333044
Related