如何仅替换与 sed 中多个模式匹配的行?

gas*_*ter 8 sed

$ echo -e 'CH12\nCH23au' | sed '/^CH/s=^=<b>='
<b>CH12
<b>CH23au
Run Code Online (Sandbox Code Playgroud)

我知道我可以匹配以CHby开头的行,^CH但如何匹配多个模式?

例子:

输入:

CH12
CH23au
Run Code Online (Sandbox Code Playgroud)

输出:

CH12
<b>CH23au
Run Code Online (Sandbox Code Playgroud)

如何只放在<b>^CHau在线的地方?

Uwe*_*Uwe 9

If the CH must occur at the beginning of the line, the order of CH and au is fixed, so you can look for ^CH.*au.

$ echo -e 'CH12\nCH23au' | sed '/^CH.*au/s=^=<b>='
CH12
<b>CH23au
$
Run Code Online (Sandbox Code Playgroud)

If the order of the two patterns is not fixed, one could do something like

sed -e '/pattern1/{;/pattern2/s/old/new/;}'
Run Code Online (Sandbox Code Playgroud)

but the perl solution

perl -pe 'if (/pattern1/ && /pattern2/) {s/old/new/;}'
Run Code Online (Sandbox Code Playgroud)

is probably more readable.


Sté*_*las 5

另一种方法:

sed -e '/^CH/!b' -e '/au/!b' -e 's/^/<b>/'
Run Code Online (Sandbox Code Playgroud)

b(如果没有给出任何标签参数,则分支到最后)就像continuenext在其他语言中。所以上面是这样的:

for (; line = readline(); print line) { # The implicit loop in sed
  if (!/^CH/) continue;
  if (!/au/) continue;
  line =~ s/^/<b>/
}
Run Code Online (Sandbox Code Playgroud)