mercredi 21 mars 2018

Print only the matched line when process line by line from a file

I have the below code, and its input file "fruits.txt" has following values.

Apple
Mango
Grapes
Bananas
Avocado

I'm getting the output as below;

Grapes not in list Strawberry not in list Grapes not in list Strawberry not in list Grapes Strawberry not in list Grapes not in list Strawberry not in list Grapes not in list Strawberry not in list Grapes not in list Strawberry not in list

However, i'm actually looking for an output like this, please help!

Expected result as follows.

Grapes Strawberry not in list

use strict;
use warnings;

open (FILE,"fruits.txt");
    while (<FILE>) {
     if (/Grapes/) {
     print $_;
     } else { print "Grapes not in list\n";}
     if (/strawberry/i) {
     print $_;
     } else { print "Strawberry not in list\n";}
     }
     close FILE;

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire