繁体   English   中英

删除SED中指定标记内匹配前后的行

[英]Delete lines before and after a match within a specified tags in SED

需要在标记内的匹配模式之前和之后删除

< mds:insert> 
    < attributeValues>
        < AttrNames
            < Item Value="MyContact_c"/>
        < /AttrNames>
    < /attributeValues>
< /mds:insert>

运用

sed -i -n '/MyContact_c/{s/.*//;x;d;};x;p;${x;p;}' $file

只删除匹配模式前后的行,需要删除mds中的所有内容:insert tag ...任何指针都会有所帮助。

它不是sed ,但这里是一个ex使用您发布作为文件内容片断$file

kitsune:~$ printf '%s\n' 'set ic
1;/="MyContact_c"/<|?<mds:insert?+;/<\/mds:insert>/-d
%p' | ex -s $file

输出:

<mds:insert>
</mds:insert>

这将删除该部分的第一个实例后打印文件的剩余部分。 如果要为所有实例完成此操作,命令行将如下所示:

'set ic
g/="MyContact_c"/<|?<mds:insert?+;/<\/mds:insert>/-d
%p'

如果要对多个文件执行此操作,可以在shell脚本的for循环中使用它。 如果你做这样的事情,你自然会想要一个备份副本,所以如果你打算覆盖它,请确保在更改之前复制该文件。

顺便说一下,如果你曾经使用Vim甚至vi,这些命令用于保存,退出等。值得将ex添加到你的知识工具箱恕我直言。

编辑

C Shell用户不能按原样使用这些命令,因为它们包含引用的换行符,这在C shell中是不允许的。 相反,您可以像这样修改第一个命令:

kitsune:~% printf '%s\n%s\n%s\n' 'set ic' '1;/="MyContact_c"/<|?<mds:insert?+;/<\/mds:insert>/-d' '%p' | ex -s $file

您也可以使用其他字符串执行相同的操作。

免责声明:我自己不是C shell用户,所以可能有更好的方法,但我不知道。

这是在sed中执行此操作的一种方法:

sed -e ':a' -e '/ mds:insert/!{p;d;}' -e 'N;/\/mds:insert/{/MyContact_c/!p;d;};ba' filename

编辑:

你和我可能正在使用不同版本的sed或其他东西。 我们来试试吧:

sed -e '/ mds:insert/!{p;d;}' filename

它不会做任何有趣的事情,但我想知道它是否会产生错误。

这是用awk做的一种方法

awk '{a[NR]=$0} /MyContact_b/ {f=NR} END {for (i=1;i<=NR;i++) if (i+2<f || i-2>f || !f) print a[i]}' file
< mds:insert>
< /mds:insert>

它跳过2线和两条前后pattern ,如果它的发现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM