搜索特定字符串并在特定字符串之间打印 - Linux Shell Script

时间:2016-07-26 16:49:41

标签: linux shell

这是我的档案。

'#### 
OutOfmemory is the error which has occured
Log Error
Sample
'####
Incident Dump Executor 
Test
Notinhg
'####
Sample
test
'####
OutOfmemory Sample
This is what i want
'####

从这个文件中,我想找到OutOfmemory,一旦发现我需要打印####

之间的行

OutOfmemory出现两次,所以我想要这样的输出:

'#### 
OutOfmemory is the error which has occured
Log Error
Sample
'####

'####
OutOfmemory Sample
This is what i want
'####

我不希望输出中剩余的行。

2 个答案:

答案 0 :(得分:0)

grep-A(之后)和-B(之前)选项一起使用,您可以指定在找到匹配之后/之前显示的行数。 假设您的文件名为foo,您可以这样做:

cat foo | grep -i -B 1 -A 2 "OutOfmemory"

答案 1 :(得分:0)

使用gnu-awk你可以这样做:

awk -v RS="'####" 'BEGIN{ORS=RS "\n\n"} /OutOfmemory/{print RT $0}' file

'####
OutOfmemory is the error which has occured
Log Error
Sample
'####

'####
OutOfmemory Sample
This is what i want
'####