Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grepping for overlapping pattern matches

Tags:

regex

grep

unix

This is what I'm running

grep -o ',[tcb],' <<< "r,t,c,q,c b,b,"

The output is

,t,
,b,

But I want to get

,t,
,c,
,b,

(I do not want the b without a preceding , or the c without a trailing , to be matched)

Because ,[tcb], should be found in 'r",t,"c,q b,b,' 'r,t",c,"q b,b,' and 'r,t,c,q b",b,"'

But it seems that when the , is included in the first pattern match then grep does not look for this in the second instance of the pattern match

Is there a way around this or is grep not meant to do this

like image 757
Sam Avatar asked Jan 23 '26 17:01

Sam


1 Answers

You can use awk instead of grep for this with record separator as comma:

awk -v RS=, '/^[tcb]$/{print RS $0 RS}' <<< "r,t,c,q,c b,b,"

,t,
,c,
,b,
like image 86
anubhava Avatar answered Jan 27 '26 00:01

anubhava