从bash中删除特定标记中的所有字符串

时间:2016-01-19 12:34:02

标签: regex bash

假设我有这个文件:

this is 1th line
this is 2th line
<<EOM
this is 3th line
EOM>>
this is 4th line
<<EOM
this is 5th line
EOM>>
this is 6th line

无论如何都要在bash中运行命令来获取:

this is 3th line
this is 5th line

并在没有<<EOM的情况下获取全文?

2 个答案:

答案 0 :(得分:4)

这应该有效:

$ sed -n '/<<EOM/,/EOM>>/p' file | grep -v EOM || cat file

我的意思是......

  1. 它应该在EOM标记之间打印行如果它们存在 或者:
  2. 如果没有EOM,则打印整个文件
  3. 而且......这样更好(避免删除包含EOM的标记之间的行):

    $ sed -n '/<<EOM/,/EOM>>/p' file | grep -vw '<<EOM\|EOM>>' || cat file
    

答案 1 :(得分:2)

grep -q "<<EOM" file && awk '/<<EOM/{flag=1;next}/EOM>>/{flag=0}flag' file || cat file

如果在<<EOM中找到file,则会在<<EOMEOM>>之间打印awk行。仅cat <{1}} file