我有一个文件,它将HTML风格的注释与其真实文本交替使用:
<!-- Here's a first line -->
Here's a first line
<!-- Here's a second line -->
Here's a third line
如果一个注释除了标签本身之外与下面的行完全相同,我想删除它,但在其他情况下保留它:
Here's a first line
<!-- Here's a second line -->
Here's a third line
我在这里读过类似的问题,但无法推断出我的情况的解决方案。
sed '/^<!-- (.*) -->$/N;s/^<!-- (.*) -->n1$/1/'
#
# /^<!-- (.*) -->$/ match an HTML comment as its own line, in which case
# N; add the next line to the pattern space and keep going
#
# s/^<!-- (.*) -->n1$/ detect a comment as you
# 1/ described and replace it
# appropriately
如图所示:
$ sed '/^<!-- (.*) -->$/N;s/^<!-- (.*) -->n1$/1/' <<EOF
> <!-- Foo -->
> Foo
> <!-- Bar -->
> Baz
> <!-- Quux -->
> Quux
>
> Something
> Something
> Another something
> EOF
提供:
Foo
<!-- Bar -->
Baz
Quux
Something
Something
Another something
您可能需要对此进行调整以处理缩进,但这不应该太令人惊讶。您可能还想切换到sed -r
,这将要求括号不转义。
您可以使用此awk
:
awk '/<!--.*?-->/{h=$0; gsub(/ *(<!--|-->) */, ""); s=$0; next}
$0!=s{$0=h ORS $0} 1' file.html
Here's a first line
<!-- Here's a second line -->
Here's a third line
这可能对你有用(GNU sed):
sed -r '$!N;/<!-- (.*) -->n1$/!P;D' file
这将比较整个文件中请求条件的所有连续行,如果找到,则不打印对中的第一行。
注意:这迎合了的连续评论行