Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed: skip match if has already been replaced

Tags:

bash

sed

I am playing with text automatically converting to markup. I can make sed enclose some inline code:

echo "this is inline_code test 1_2 (_)" | sed -re "s/([a-z0-9]+_[a-z0-9]+)/\`\1\`/g;s/[_]/\\\\_/g"

Result:

this is `inline\_code` test `1\_2` (\_)

But I would like sed to stop replacing text that it already matched (I tried branching with t):

echo "this is inline_code test 1_2 (_)" | sed -re "s/([a-z0-9]+_[a-z0-9]+)/\`\1\`/g;t;s/[_]/\\\\_/g"

Result:

this is `inline_code` test `1_2` (_)

But what I really wanted was this:

this is `inline_code` test `1_2` (\_)
like image 792
thomas Avatar asked Jan 23 '26 16:01

thomas


1 Answers

In this particular case you can guard the underscores that aren't meant to be replaced a second time by temporarily replacing them with a character (like newline) that wouldn't normally appear in the pattern space:

sed -E 's/([a-z0-9]+)_([a-z0-9]+)/`\1\n\2`/g; s/_/\\_/g; s/\n/_/g'
like image 98
oguz ismail Avatar answered Jan 25 '26 09:01

oguz ismail



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!