2

我目前有一个包含以下内容的文件:

<refrigerator>
    <food="watermelon" location="topShelf" />
    <!--
    <food="mango" location="bottomShelf" />
    --> 
    <!--
    <food="orange" location="middleShelf" />
    --> 
</refrigerator>

如何使用 'sed' 删除<!---->以便从文件中取消注释“mango”?但是,如果文件中还有其他行注释,我希望它们保持注释吗?

谢谢!

4

3 回答 3

3

sed可以尝试:

sed '/<!--/{ N; N; s/.*\n\(.*food="mango".*\)\n.*-->.*/\1/; }' file
于 2013-02-26T00:09:37.173 回答
3

sed不是正确的工具(默认情况下不是多行),尝试使用,这更适合这种情况:

$ perl -i -0777 -pe 's/\s*<!--\s*\n(.*?food="mango".*?)\n\s*-->/\n$1/' file.txt

输出

<refrigerator>
    <food="watermelon" location="topShelf" />
    <food="mango" location="bottomShelf" /> 
    <!--
    <food="orange" location="middleShelf" />
    --> 
</refrigerator>

解释

  • -iswitch就地编辑文件(就像sed -i
  • -0777一次读取整个文件(也可以按段落读取-00
  • -p假设 "while (<>) { ... }" 循环程序,并打印换行符
  • s///sed类似替换的骨架
  • \s是 Perl 的空白字符
  • .*?代表不贪心匹配
  • $1与 sed 相同\1捕获的部分)

文档

于 2013-02-26T00:23:30.610 回答
1

这是我使用创建的解决方案awk

识别在xml元素内具有“连接器服务器=”的所需元素,但不在具有<!--

脚本.awk:

/<!--/ && /-->/ {print;next;}
/-->/ && insideComment {
    if (insideDesiredElement) {
        sub("<!--","",firstLine);
        sub("-->","");
        insideDesiredElement = 0;
    }
    print firstLine ORS commentBlock $0;
    insideComment = 0;
    next;
}
/<!--/ {
    insideComment = 1;
    commentBlock = "";
    firstLine = $0;
    next;
}
insideComment {
    if ($0 ~ "Connector server=") insideDesiredElement = 1;
    commentBlock = commentBlock $0 ORS;
    next;
}1

跑步:

awk -f script.awk input.xml
于 2020-05-25T23:23:46.520 回答