maz
maz

Reputation: 3

print lines after finding a key word in perl

I have a variable $string and i want to print all the lines after I find a keyword in the line (including the line with keyword)

$string=~ /apple /;

I'm using this regexp to find the key word but I do not how to print lines after this keyword.

Upvotes: 0

Views: 2600

Answers (3)

choroba
choroba

Reputation: 241998

Just keep a flag variable, set it to true when you see the string, print if the flag is true.

perl -ne 'print if $seen ||= /apple/'

Upvotes: 1

mkHun
mkHun

Reputation: 5927

If your data in scalar variable we can use several methods

Recommended method

($matching) =  $string=~ /([^\n]*apple.+)/s;
print "$matching\n";

And there is another way to do it

$string=~ /[^\n]*apple.+/s; 
print $&; #it will print the data which is match.

If you reading the data from file, try the following

while (<$fh>)
{
  if(/apple/)
  {
     print <$fh>;
  }
}

Or else try the following one liner

perl -ne 'print <> and exit if(/apple/);' file.txt

Upvotes: 0

Dave Cross
Dave Cross

Reputation: 69314

It's not really clear where your data is coming from. Let's assume it's a string containing newlines. Let's start by splitting it into an array.

my @string = split /\n/, $string;

We can then use the flip-flop operator to decide which lines to print. I'm using \0 as a regex that is very unlikely to match any string (so, effectively, it's always false).

for (@string) {
  say if /apple / .. /\0/;
}

Upvotes: 1

Related Questions