Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find recurring pattern with `sed`

Tags:

regex

unix

sed

I am using GNU bash 4.3.48

I expected that

echo "23S62M1I19M2D" | sed 's/.*\([0-9]*M\).*/\1/g'

would output 62M19M... But it doesn't.

sed 's/\([0-9]*M\)//g' deletes ALL [0-9]*M and retrieves 23S1I2D. but the group \1 is not working as I thought it would.

sed 's/.*\([0-9]*M\).*/ \1 /g', retrieves M...

What am I doing wrong?

Thank you!

like image 285
aerijman Avatar asked Nov 19 '25 04:11

aerijman


1 Answers

With your shown samples and with awk you could try following program.

echo "23S62M1I19M2D" | 
awk '
{
  val=""
  while(match($0,/[0-9]+M/)){
    val=val substr($0,RSTART,RLENGTH)
    $0=substr($0,RSTART+RLENGTH)
  }
  print val
}
'

Explanation: Simple explanation would be, using echo to print values and sending it as a standard input to awk program. In awk program using its match function to match regex mentioned in it(/[0-9]+M) running loop to find all matches in each line and printing the collected matched values at last of each line.

like image 60
RavinderSingh13 Avatar answered Nov 20 '25 18:11

RavinderSingh13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!