【问题标题】:Search for particular string and print between particular strings -- Linux Shell Script搜索特定字符串并在特定字符串之间打印——Linux Shell Script
【发布时间】:2016-07-26 16:49:41
【问题描述】:

这是我的文件。

'#### 
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
'####

我不想在我的输出中留下剩余的行。

【问题讨论】:

  • 这个问题难以辨认。如果您希望人们帮助您,请对代码使用代码格式。另外,我看你没问问题。 StackOverflow 是针对精确问题的,所以你不仅要陈述你的问题,还要展示你目前的方法是什么,以及你到底在哪里遇到了问题。
  • 抱歉我现在改了
  • 就算法而言,保留一个运行缓冲区和一个“OutOfMemory”标志就足够了。逐行读取,将它们添加到缓冲区。如果它们包括“OutOfMemory”,则将该标志设置为 true。如果它们匹配“###”,如果标志为真,则打印整个缓冲区,然后将标志设置为假,清除缓冲区并继续。

标签: linux shell


【解决方案1】:

使用 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
'####

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      相关资源
      最近更新 更多