LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Perl to find regex and print following 5 lines after regex (http://www.linuxquestions.org/questions/linux-newbie-8/perl-to-find-regex-and-print-following-5-lines-after-regex-829153/)

casperdaghost 08-29-2010 12:02 PM

Perl to find regex and print following 5 lines after regex
 
Alot of time I use a perl one liner like a grep at the end of a cat or more to print specific text from a log or config file. It works great.

more myfile | perl -nle 'print /(regex)/'


what would be awesome is if I could find and print the regex, and the 5 lines following that regex then stop, find the next matching regex and print the next five lines - until end of file.

I think there is a way to do it in Awk and Sed - if there is there should be a way to do it in Perl.

grail 08-29-2010 12:30 PM

Why not just use grep -A 5 and your regex.

Tinkster 08-29-2010 12:44 PM

Quote:

Originally Posted by casperdaghost (Post 4081535)
Alot of time I use a perl one liner like a grep at the end of a cat or more to print specific text from a log or config file. It works great.

more myfile | perl -nle 'print /(regex)/'


what would be awesome is if I could find and print the regex, and the 5 lines following that regex then stop, find the next matching regex and print the next five lines - until end of file.

I think there is a way to do it in Awk and Sed - if there is there should be a way to do it in Perl.


You may find perlmonks helpful.

In the link above is a snippet from Randal himself
that should give you exactly what you want.


Cheers,
Tink

ghostdog74 08-29-2010 08:08 PM

Quote:

Originally Posted by casperdaghost (Post 4081535)
Alot of time I use a perl one liner like a grep at the end of a cat or more to print specific text from a log or config file. It works great.

more myfile | perl -nle 'print /(regex)/'

tip for you, there's a tool called a2p you can use to translate awk to Perl code. Eg, awk
Code:

c&&c--;/^Alas/{c=5}
put this as a script, eg myscript.awk, then on command line
Code:

$ a2p test.awk

#!/usr/bin/perl
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
    if $running_under_some_shell;
                        # this emulates #! processing on NIH machines.
                        # (remove #! line above if indigestible)

eval '$'.$1.'$2;' while $ARGV[0] =~ /^([A-Za-z_0-9]+=)(.*)/ && shift;
                        # process any FOO=bar switches

while (<>) {
    print $_ if $c && $c--;;
    if (/^Alas/) {
        $c = 5;
    }
}

what you need is the while(<>) part.
Code:

$ cat test1.pl

#!/usr/bin/perl -w
while (<>) {
    print $_ if $c && $c--;
    if (/^Alas/) {
        $c = 5;
    }
}

$ perl test1.pl file



All times are GMT -5. The time now is 03:06 AM.