FreeKB - 0 if file contains match get next line in Perl
if file contains match get next line in Perl

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

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |