如何替换文本中的连续模式
how to replace continuous pattern in text
我有类似 1|2|3||| 的文本,并尝试将每个 || 替换为 |0|,我的命令如下
echo '1|2|3|||' | sed -e 's/||/|0|/g'
但得到结果1|2|3|0||,模式只被替换一次。
谁能帮我改进命令,谢谢
这可能适合您 (GNU sed):
sed 's/||/|0|/g;s//[0]/g' file
或:
sed ':a;s/||/|0|/g;ta' file
替换需要操作两次,因为替换中有部分匹配。
只做2次
l_replace='s#||#|0|#g'
echo '1|2|3||||||||4||5|||' | sed -e "$l_replace;$l_replace"
在每个 Unix 机器上的任何 shell 中使用任何 sed 或任何 awk:
$ 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|"));}1'
1|2|3|0|0|
我有类似 1|2|3||| 的文本,并尝试将每个 || 替换为 |0|,我的命令如下
echo '1|2|3|||' | sed -e 's/||/|0|/g'
但得到结果1|2|3|0||,模式只被替换一次。
谁能帮我改进命令,谢谢
这可能适合您 (GNU sed):
sed 's/||/|0|/g;s//[0]/g' file
或:
sed ':a;s/||/|0|/g;ta' file
替换需要操作两次,因为替换中有部分匹配。
只做2次
l_replace='s#||#|0|#g'
echo '1|2|3||||||||4||5|||' | sed -e "$l_replace;$l_replace"
在每个 Unix 机器上的任何 shell 中使用任何 sed 或任何 awk:
$ 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|"));}1'
1|2|3|0|0|