2

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
  • I am fairly certain you will need to grep twice, once for each capture group using lookahead and lookbehinds (or use something other than grep).
    – jordanm
    Commented May 24, 2021 at 17:11

1 Answer 1

4

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
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.