Linux 使用 sed 删除文本块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6945621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:28:29  来源:igfitidea点击:

Using sed to remove a block of text

linuxunixsed

提问by Scott C Wilson

I have a block of text that looks like this:

我有一个看起来像这样的文本块:

    <!-- BOF CLEAN -->
... a bunch of stuff 
    <!-- EOF CLEAN -->

I'd like to remove this entire block. What's the sed command?

我想删除整个块。sed 命令是什么?

采纳答案by Maxim Egorushkin

$ cat text 
abc
    <!-- BOF CLEAN -->
... a bunch of stuff
    <!-- EOF CLEAN -->
def
$ sed '/<!-- BOF CLEAN -->/,/<!-- EOF CLEAN -->/d' text 
abc
def

http://www.catonmat.net/blog/sed-one-liners-explained-part-three/

http://www.catonmat.net/blog/sed-one-liners-explained-part-three/

回答by Nadir Latif

To remove all the text starting from and including <!-- BOF CLEAN -->and ending at and including <!-- EOF CLEAN -->, use following sed command:

要删除从 和包括 开始并<!-- BOF CLEAN -->以和包括结束的所有文本 <!-- EOF CLEAN -->,请使用以下 sed 命令:

sed -i '/<!-- BOF CLEAN -->/,/<!-- EOF CLEAN -->/d' file_name;

Reference: Delete text or paragraph between two sections using sed

参考:使用 sed 删除两个部分之间的文本或段落

回答by Scott C Wilson

These days I am using the /smodifier to do this. I noticed no one mentioned that. I use markup with is free of spaces too like

这些天我正在使用/s修改器来做到这一点。我注意到没有人提到这一点。我使用的标记也没有空格

{bof-nf} ... a bunch of stuff {eof-nf}

{bof-nf} ... a bunch of stuff {eof-nf}

So for example, to remove this block, use

例如,要删除此块,请使用

$newcontent = preg_replace("/\{bof-nf\}(.*)\{eof-nf\}\\n/s", "", $newcontent);

$newcontent = preg_replace("/\{bof-nf\}(.*)\{eof-nf\}\\n/s", "", $newcontent);

To keep the block but remove the tags, use

要保留块但删除标签,请使用

$newcontent = preg_replace("/\{bof-nf\}.*\\n/", "", $newcontent); $newcontent = preg_replace("/\{eof-nf\}.*\\n/", "", $newcontent);

$newcontent = preg_replace("/\{bof-nf\}.*\\n/", "", $newcontent); $newcontent = preg_replace("/\{eof-nf\}.*\\n/", "", $newcontent);