Hi,
I would like to know how to grep the first occurrence of a string above(upwards) a reference string.
for (e.x.)in the below set, I would like to get the first occurrence of "AAA" above "XXX".
AAA
BBB
AAA
CCC
XXX
Thanks,
Venkat
To the OP - if you rephrase your problem, you have the solution almost there:
I want to keep track of a pattern I seek for, and output the found string after finding a reference string
which is what ww did for you above already. Hence a possible solution is
#!/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 = '';
}
}
to be used as
$ perl grep.pl AAA XXX example.txt
which invoked upon this example.text
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
produces this:
example.txt: ' 5 second AAA'
example.txt: ' 10 third AAA'
Lines 2 and 16 are not printed. If you use the commented alternative, line 2 is printed instead of line 5.
perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
|