组合2个或更多`grep -A`输出

时间:2017-10-30 06:02:01

标签: shell grep

这是我的样本数据

Apple 13
Apple 37
Apple 341
Apple 27B
Apple 99
Banana 00
Banana 988
Banana 507
Banana 11
Banana 11A

我想得到像这样的输出

Apple 13
Apple 37
Apple 341
Banana 00
Banana 988

问题是我只能用开关-A 2进行一次grep

root@Ubuntu:/tmp# grep -A 2 'e 1' data.txt  
Apple 13
Apple 37
Apple 341
root@Ubuntu:/tmp# 

另一个grep -A 1

root@Ubuntu:/tmp# grep -A 1 'a 0' data.txt  
Banana 00
Banana 988
root@Ubuntu:/tmp# 

我一直在尝试使用egrep,但我没有得到我想要的输出。

root@Ubuntu:/tmp# egrep 'e 1|a 0' data.txt 
Apple 13
Banana 00
root@Ubuntu:/tmp# 

我想在Apple 13之后再增加两行,在Banana 00之后增加一行

请告知

3 个答案:

答案 0 :(得分:2)

使用GNU sed:

sed -n '/e 1/{N;N;p}; /a 0/{N;p}' file

输出:

Apple 13
Apple 37
Apple 341
Banana 00
Banana 988

请参阅:man sed

答案 1 :(得分:2)

我建议 awk sed 来解决这些问题

使用 awk

wb <- createWorkbook()
addWorksheet(wb, sheetName = "sheet1")

writeData(wb, sheet = 1, x = df, startCol = 2, startRow = 2)
writeData(wb, sheet = 1, x = df2, startCol = 2, startRow = 24)

saveWorkbook(wb, file = "path/to/file.xslx")

$ awk ' /e 1/{i=1; t=3} /a 0/{i=1; t=2} i++<=t' file Apple 13 Apple 37 Apple 341 Banana 00 Banana 988 :迭代器
i:阈值

t:如果字符串包含/e 1/{i=1; t=3},请设置e 1i=1
t=3因为总共需要打印3行(包括匹配行)

t=3:如果字符串包含/a 0/{i=1; t=2},则设置a 0i=1

t=2:如果确实如此,则打印行。 i++<=t每次检查后增加i++

答案 2 :(得分:1)

我没有任何想法通过一个命令来解决这个问题。如果您不介意使用几个命令,请使用以下内容,

grep -A 2 "e 1" test.txt && grep -A 1 "a 0" test.txt