Bootstrap FreeKB - Perl (Scripting) - if file contains match get next line
Perl (Scripting) - if file contains match get next line

Updated:   |  Perl (Scripting) articles

Let's say you have a file (fruit.txt) that contains fruit.

apple
banana
orange
pineapple

 

This script will loop through each line in fruit.txt. If a line contains "banana", then the line containing banana and the next line are printed. The "if statement" prints the line containing banana and the "elsif statement" prints the next line.

#!/usr/bin/perl

use strict;
use warnings;

my $file = "fruit.txt";
my $flag = 0;

open(FH, "<", $file) or die "cannot open $file $! \n";

while (my $line = <FH>) {
  if ($line =~ /banana/ ) {
    print $line;
    $flag = 1;
  }
  elsif ($flag eq "1") {
    print $line;
    $flag = 0;
  }
}

close FH;

 

Running this script should produce the following.

banana
orange

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 2d45d6 in the box below so that we can be sure you are a human.