sed:替换任意次数的特定模式

shi*_*iva 8 sed

鉴于此输入:

 "hell -- 'this -- world --is'-- beautiful' --thanks-- we'-- are-- here" 
Run Code Online (Sandbox Code Playgroud)

我想用 'XXX' 替换单引号之间的每个 '--' 使用sed. 它应该提供以下输出:

输出:“地狱——'这个 XXX 世界 XX-Xis'--美丽的 XX-Xthanks XXX 我们'——在这里”

替换次数可能未知(最多无穷大)。

Hyp*_*ppy 9

您想在末尾使用 /g 开关来解析每行多个替换。

sed s/--/X-X-X/g
Run Code Online (Sandbox Code Playgroud)


Den*_*son 8

编辑:

使用您的新要求:

sed 's/\o47[^\o47]*\o47/\n&\n/g;:a;s/\(\n\o47[^\n]*\)--/\1X-X-X/;ta;s/\n//g' input file
Run Code Online (Sandbox Code Playgroud)

编辑2:

对于某些sed不喜欢分号的版本:

sed -e 's/\o47[^\o47]*\o47/\n&\n/g' -e ':a' -e 's/\(\n\o47[^\n]*\)--/\1X-X-X/' -e 'ta' -e 's/\n//g' inputfile
Run Code Online (Sandbox Code Playgroud)

如果您sed也不支持八进制转义码:

sed -e "s/'[^']*'/\n&\n/g" -e ':a' -e "s/\(\n'[^\n]*\)--/\1X-X-X/" -e 'ta' -e 's/\n//g' inputfile
Run Code Online (Sandbox Code Playgroud)

原答案:

您通常应该使用单引号将sed脚本括起来,这样您就不必转义可能对 shell 来说很特殊的字符。尽管在这种情况下没有必要,但养成一个好习惯。

sed 's/--/X-X-X/g' inputfile
Run Code Online (Sandbox Code Playgroud)

或者

var="hell --this -- world is --beaut--iful"
newvar=$(echo "$var" | sed 's/--/X-X-X/g')
Run Code Online (Sandbox Code Playgroud)

如果没有g修饰符,则在每行输入的第一个匹配项上执行替换。当g使用时,在输入的每行中的每个匹配项被替换。您还可以替换特定匹配项:

$ var="hell --this -- world is --beaut--iful"
$ echo "$var" | sed 's/--/X-X-X/2'
hell --this X-X-X world is --beaut--iful
Run Code Online (Sandbox Code Playgroud)


Dan*_*eck 5

$ echo "hell --this -- world is --beaut--iful" | sed s"/--/X-X-X/g"
hell X-X-Xthis X-X-X world is X-X-XbeautX-X-Xiful
Run Code Online (Sandbox Code Playgroud)

关键是g开关:它导致sed替换所有出现的事件。