$ echo -e 'CH12\nCH23au' | sed '/^CH/s=^=<b>='
<b>CH12
<b>CH23au
Run Code Online (Sandbox Code Playgroud)
我知道我可以匹配以CH
by开头的行,^CH
但如何匹配多个模式?
例子:
输入:
CH12
CH23au
Run Code Online (Sandbox Code Playgroud)
输出:
CH12
<b>CH23au
Run Code Online (Sandbox Code Playgroud)
如何只放在<b>
有^CH
和au
在线的地方?
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.
另一种方法:
sed -e '/^CH/!b' -e '/au/!b' -e 's/^/<b>/'
Run Code Online (Sandbox Code Playgroud)
b
(如果没有给出任何标签参数,则分支到最后)就像continue
或next
在其他语言中。所以上面是这样的:
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)