Home > Enterprise >  how to replace continuous pattern in text
how to replace continuous pattern in text

Time:10-17

i have text like 1|2|3||| , and try to replace each || with |0|, my command is following

      echo  '1|2|3|||'  | sed -e 's/||/|0|/g' 

but get result 1|2|3|0||, the pattern is only replaced once.

could someone help me improve the command, thx

CodePudding user response:

Just do it 2 times

l_replace='s#||#|0|#g'
echo  '1|2|3||||||||4||5|||'  | sed -e "$l_replace;$l_replace"

enter image description here

CodePudding user response:

This might work for you (GNU sed):

sed 's/||/|0|/g;s//[0]/g' file

or:

sed ':a;s/||/|0|/g;ta' file

The replacement needs to actioned twice because part of the match is in the replacement.

CodePudding user response:

Using any sed or any awk in any shell on every Unix box:

$ echo  '1|2|3|||'  | sed -e 's/||/|0|/g; s/||/|0|/g'
1|2|3|0|0|

$ echo  '1|2|3|||'  | awk '{while(gsub(/\|\|/,"|0|"))l}1'
1|2|3|0|0|
  • Related