如何使用Unix grep删除整个不需要的文本块?

如何使用Unix grep删除整个不需要的文本块?,unix,grep,Unix,Grep,我已经尝试了很多,但是仍然找不到更聪明的方法来做这件事 例如: ### this is the whole block structure ### text_text_text text_text_text text_text_text apple ### another block ### text_text_text text_text_text text_text_text orange 执行less | grep-B3“apple”| less将返回: text_text_text t

我已经尝试了很多,但是仍然找不到更聪明的方法来做这件事

例如:

### this is the whole block structure ###
text_text_text
text_text_text
text_text_text
apple
### another block ###
text_text_text
text_text_text
text_text_text
orange
执行
less | grep-B3“apple”| less
将返回:

text_text_text
text_text_text
text_text_text
apple
但现在我的要求是我不想要这个区块(苹果)。我肯定我不想要什么,但不确定我想要什么。所以我不能这么做

less <file_name> | grep -B3 "orange" |less
less | grep-B3“橙色”| less
如果我要:

less <file_name> | grep -v "apple" | less
less | grep-v“apple”| less
然后只删除与apple相关的单行,与apple相关的块将保留在那里

我试过了

less <file_name> | grep -v -B3 "apple" | less
less | grep-v-B3“苹果”| less
但这似乎不起作用

那么,有什么办法可以帮我消除与苹果有关的障碍呢

删除不需要的块的一种方法是使用
tac
sed
。说:

tac <filename> | sed '/apple/,+3d' | tac
为您的样本数据


说明:
tac
反转文件中的行
/apple/,+3
将匹配
apple
和接下来的3行
d
delete
命令

因为您需要删除模式
apple
和它前面的3行;我们反转文件中的行,找到
apple
,删除它和接下来的3行,然后再次反转这些行以获得所需的结果


您可能还希望使用
awk
引用.p>,并假设每个块有5条记录长

cat file
### anoter block ###
text_text_text
text_text_text
text_text_text
banan
### this is the whole block structure ###
text_text_text
text_text_text
text_text_text
apple
### another block ###
text_text_text
text_text_text
text_text_text
orange
awk'{a[NR]=$0}/apple/{f=NR}END{for(i=1;i使用awk:

awk '/^apple$/{cs=0;next} 
           { c[cs++]=$0 }
    cs > 3 {
       print c[0];
       for (i=0;i<3;i++){c[i]=c[i+1]}; cs--;
    }
    END    { for (i=0;i<cs;i++){print c[i]} }' input
awk'/^apple$/{cs=0;next}
{c[cs++]=$0}
cs>3{
打印c[0];

对于(i=0;我使用
less
而不是
cat
并不能让你真正摆脱UOOC的指控-无用地使用
cat
。你应该使用
grep…| less
。嗨,谢谢,我发现你的方法可能对我有用。我可能需要修改一些,以获得最终的预期输出。但你能解释一下为什么,+有3d吗?我想完全理解这一点。非常感谢。@user2919338为答案添加了一个解释。如果苹果上面有另一个块,这就不起作用了
block@Jotne你试过了吗?你能举个例子吗?不过似乎对OP有用。(顺便说一句,上面的答案中有足够的解释来说明这是如何工作的。)试图在你的<代码>苹果<代码>苹果<代码>你的<代码>苹果苹果<代码>你的以上你的以上你的以上你的<代码>苹果<代码>苹果公司的以上你的以上你的以上你的以上你的上试加一块块块,你的以上你的以上你的以上你的以上你的以上你的以上你的以上你的以上你的以上你的以上你的以上你的你的以上你的你的你的<<代码>你的你的代码>你的你的代码>你的你的上面,你的你的你的你的你的你的你的你的代码>你的上面,你的上面,你的你的你的你的你的你的你的上面,你的你的你的你的代码>你的你的你的你的代码>你的你的你的代码>你的苹果<代码>你的苹果<代码>苹果<代码>苹果<你的苹果<你的苹果<你的苹果<你的苹果<你的苹果<_文本橙色
awk '{a[NR]=$0} /apple/ {f=NR} END {for (i=1;i<=NR;i++) if (i<f-4 || i>f) print a[i]}'
### anoter block ###
text_text_text
text_text_text
text_text_text
banan
### another block ###
text_text_text
text_text_text
text_text_text
orange
awk '/^apple$/{cs=0;next} 
           { c[cs++]=$0 }
    cs > 3 {
       print c[0];
       for (i=0;i<3;i++){c[i]=c[i+1]}; cs--;
    }
    END    { for (i=0;i<cs;i++){print c[i]} }' input