Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pattern matching

Status
Not open for further replies.
May 3, 2002
633
US
Back to something that ksh isn't really suited for. I am trying to match any number of string occurrences in a 200,000+ line file and one the line matching the string is found, print the matching line plus the next 16 lines. There can be multiple string matches in the file.

I was wondering if it is possible to use something similar to:

perl -ne 'print if 3 .. 8' /etc/passwd

But not sure how to get the next 16 lines after a match is found. Thanks for any help.
 
I have two options for you depending on what your requirements are. What I wasn't sure about is what happens if the string that you are looking for exists in one of the 16 line following the original match. Does that reset the 'counter' to get the 16 lines following the new string? or should the 16 lines be ignored as to their content?

That said. Here are the two options
Code:
perl -ne 'print and $i++ if /somestring/..($i>16 and not $i=0)' infile
#Or
perl -ne '/somestring/ and $i=17; print and $i-- unless $i < 0' infile
The first one ignores the content of the 16 lines and just prints them out. The second will reset the counter each time the string is encountered regardless of whether it is in one of the 16 line or not.

jaa
 
i dunno.. using my newbie coding skills.. would this work?
I use something like this in many of my scripts. I set up a counter starting at 0. then scan each line of the 200,000 line file. everytime it matches &quot;/etc/passwd&quot; it adds the counter to an array. this represents the index number for the line in the array containing the 200,000 lines. Once it scans them all, it then runs through each of those index numbers, printing them and the 16 subsequent lines... make sense? I write my code very straightforward and easy to read. you can probably make it less than half the lenght.. but I think this will work. I havn't tested it though

open(thefile, filenamehere);
@lines = <thefile>;
close(thefile);
$index = 0;
foreach $line (@lines){
if($line =~ /\/etc\/passwd/){
push(@indexes, $index);
}
$index++
}
if(@indexes){
foreach $indx (@indexes){
$temp = $indx;
for($temp; $temp < ($temp + 16); $temp++){
print $lines[$temp];
}
}
}
 
Sorry, I didn't test my code well enough. Here are the corrected statements.
Code:
perl -ne '/somestring/ and $i=17; print and $i-- if $i != 0' infile

perl -ne 'print and $i++ if /somestring/..($i>=16 and $i=-1)' infile

jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top