MikasaAckerman
MikasaAckerman

Reputation: 529

How to grep for two variables in two different line?

I have a situation where i need to find a line in a file which contains certain keyword for example ,below i am looking for foo and foobar in a file:

 Line 1 Line 1
 Line 2 foo Line 2
 Line 3 foobar Line 3
 Line 4 Line 4
 etc

and have to print both line after adding few strings. chances are that foobar may not exist but foo will always exist.

And they will only exist once.

After finding foo and foobar necessary transition need to be done.

grep m%foo%, @lines;
grep m%foobar%,@lines;

Upvotes: 0

Views: 158

Answers (2)

BOC
BOC

Reputation: 1139

your grep commands work well:

my @lines = split ("\n", <<'END');
Line 1 Line 1
 Line 2 foo Line 2
 Line 3 foobar Line 3
 Line 4 Line 4
END

my ($foo) = grep m%foo%, @lines;
my ($foobar) = grep m%foobar%,@lines;

my $res = lc $foo;
$res .= lc $foobar if defined $foobar;
print "$res\n";

IMHO doing a grep to find the needed lines, then manipulating these lines is a bad approach. The general pattern should be to iterate over the lines, to match a regexp to collect the needed data and finally to format your output. This code pattern works is ideal for 90% of file parsers.

my ($f1, $f2, $fb1, $fb2);
for my $line (@lines) {
    if ($line =~ m/(\d+) foo Line (\d+)/) {
        $f1 = $1;
        $f2 = $2;
    } elsif ($line =~ m/(\d+) foobar Line (\d+)/) {
        $fb1 = $1;
        $fb2 = $2;
    }
}

if (defined $fb1) {
    print "foo and foobar: $f1 $f2 $fb1 $fb2\n";
} else {
    print "Only foo $f1 $f2\n";
}

Upvotes: 1

l&#39;L&#39;l
l&#39;L&#39;l

Reputation: 47274

It's unclear what you are doing with the result, although you can grab both foo and foobar:

grep -noE "foo\w*"

If you want to be specific:

grep -noE "foo|foobar"

Output:

2:foo
3:foobar

Upvotes: 1

Related Questions