#!/usr/bin/perl
# file grep.pl
my $sought = shift; # from @ARGV
my $reference = shift;
$sought && $reference or die "usage: $0 soughtstring refstring files\n";
my $found;
while(<>) {
chop; # strip newline
/$sought/ and $found = $_;
# or, if you want the very first occurence, don't
# overwrite the variable (see perlop for '||='):
# /$sought/ and $found ||= $_;
if (/$reference/) {
print "$ARGV: '$found'\n" if $found;
$found = '';
}
}
####
$ perl grep.pl AAA XXX example.txt
####
1 YYY
2 first AAA
3 BBB
4 CCC
5 second AAA
6 freida
7 XXX
8 GGG
9 FFF
10 third AAA
11 XXX
12 ozymandis
13 BBB
14 blorflydick
15 XXX
16 fourth AAA
####
example.txt: ' 5 second AAA'
example.txt: ' 10 third AAA'