开发者

Conditional Multi-Line Grep Problem [closed]

开发者 https://www.devze.com 2023-03-25 07:12 出处:网络
Closed. This question is off-topic. It is not currently accepting answers. Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed. This question is off-topic. It is not currently accepting answers.

Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 11 years ago.

Improve this question

I have a very large file I want to extract lines from. I'm hoping Grep 开发者_高级运维can do the job, but I'm running into problems.

I want to return all lines that match a pattern. However, if the following line of a matched line contains the word "Raw" I want to return that line as well.

Is this doable? Or would another method be more suitable?

For example,

Input:

pattern blah blah blah

something nothing

pattern something ready

nothing Raw

A grep on "pattern" should return:

pattern blah blah blah

pattern something ready

nothing Raw

The line "nothing Raw" is included in the results because it contains "Raw" and follows the already matched line "pattern something ready".

Thanks


Something like this should work:

grep -A 1 'pattern' file.txt | grep 'pattern\|Raw'


There might be some fiendishly clever way to do this with grep. But in the time it takes to think of that, you could have already written your script in Perl.

Something like this should do the trick:

#!/usr/bin/perl
use strict;
use warnings;
my $pattern = 'pattern';
my $raw = 'Raw';
my $prevMatched = 0;
foreach my $ln (<>)
{
   if ($ln =~ /$pattern/)
   {
      print $ln;
      $prevMatched = 1;
   }
   else
   {
      if ($prevMatched && $ln =~ /$raw/)
      {
         print $ln;
      }
      $prevMatched = 0;
   }
}


Many grep implementations supports -e which you can then chain:

/usr/xpg4/bin/grep -e "^<pattern>" -e "Raw"

(But that only works if every occurrence of "Raw" is valid)

0

精彩评论

暂无评论...
验证码 换一张
取 消