Operating System - HP-UX
1828490 Members
2160 Online
109978 Solutions
New Discussion

Re: searching script help

 
SOLVED
Go to solution
Bill McNAMARA_1
Honored Contributor

searching script help

Hi all,

I've a file as follows:

2006-1-1
a 1 2 3 4 5 6
b 1 2 3 4 5 6
c 1 2 3 4 5 6
d 1 2 k 4 5 6
2007-1-2
a 1 2 g 4 5 6
d 1 2 t 4 5 6
d 1 2 t 4 5 6
e 1 2 r 4 5 6
2006--1-3
d 1 2 3 4 5 6
e 1 2 g 4 5 6
a b c d e f g
c v f 3 4 5 6

I would like to search the file to print
2006--1-3
d 1 2 3 4 5 6
e 0 0 0 4 5 6
a b c d e f g

based on first occurance of the input search string

e 0 0 0 4 5 6

ie. basically
on greping the first occurance of
e 0 0 0 4 5 6

how can I print the previous say 20 lines,
or
how can I print the previous lines up to the header 2006

Thanks for all help...
Bill
It works for me (tm)
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor

Re: searching script help

Hi Bill!

[ Long time, no hear :-)) ]

OK, try this Perl script:

# cat ./findpat
#!/usr/bin/perl
use strict;
use warnings;
my $pat = shift;
my @lines;
while (<>) {
shift @lines if $#lines > 20;
if (/$pat/) {
print for @lines;
print;
last;
}
push @lines,$_;
}

...Run it passing the pattern to match as the first argument and the file to process as the second:

# ./findpat 2006--1-3 filename

Regards!

...JRF...
spex
Honored Contributor
Solution

Re: searching script help

Bill,

Here's how to print 20 lines prior to a regex using 'ex':

$ ex -s +"g/e 0 0 0 4 5 6/-20,/e 0 0 0 4 5 6/p | q!" < infile

PCS
Peter Godron
Honored Contributor

Re: searching script help

Bill,
I'm sorry, but I don't understand the requirement.
e 0 0 0 4 5 6 is not in the file, so a grep would return nothing.

Might be easiest to get gnu grep which has a -B n option, showing n lines before the matched line.

For context grep/sed/perl solutions:
http://forums1.itrc.hp.com/service/forums/questionanswer.do?threadId=861863
http://forums1.itrc.hp.com/service/forums/questionanswer.do?threadId=793890
Oviwan
Honored Contributor

Re: searching script help

Hy

Here is also a perl script:

# cat testing.pl
#!/usr/bin/perl -w

my $search=shift;
my (@saves,@lines);

while (<>) {
if ($_ =~ /$search/) {
foreach $i (0..$#saves)
{
if ($saves[$i] =~ /^\d{4}-\d{1}-\d{1}/) {
unshift(@lines,$saves[$i]);
last;
} else {
push(@lines,$saves[$i]);
}
}

push(@lines,$_);

if ($#lines > 0){
foreach $i (0..$#lines)
{
print $lines[$i];
}
}
@lines = ();
@saves = ();
} else {
unshift(@saves,$_);

}

}
# perl testing.pl "c v f 3 4 5 6" filename
2006-1-3
a b c d e f g
e 1 2 g 4 5 6
d 1 2 3 4 5 6
c v f 3 4 5 6


Regards
Bill McNAMARA_1
Honored Contributor

Re: searching script help

GNU grep
It works for me (tm)