1844885 Members
1807 Online
110233 Solutions
New Discussion

Re: perl scripting

 
SAM_24
Frequent Advisor

perl scripting

Hi,

Could some pls. explain what this piece of code does?

perl -ne '{$n=5 if /^matched/;$n--,print $_ if $n;$n=0 if eof}' logfile

Thanks.
Never quit
6 REPLIES 6
Steven E. Protter
Exalted Contributor

Re: perl scripting

It looks for a particular string at the beginning of a line in a log file.

I think.

SEP
Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
Sachin Patel
Honored Contributor

Re: perl scripting

n=5
if "match" found at start of line then
n-- i.e n=4
print line

then I am confuse. may be running until end of logfile

Sachin
Is photography a hobby or another way to spend $
Josh Owings
Frequent Advisor

Re: perl scripting

It looks at logfile and sets $n to 5 every time it sees a line starting with 'matched'. It then decrements $n to 4 and prints the line. Every following line is printed and $n is decremented until $n is zero. Keep in mind that $n is decremented before the print. All lines are then ignored (not printed) until another line beginning with 'matched' is found.
Josh Owings
Frequent Advisor

Re: perl scripting

I forgot to give a possible use.

Suppose you have a log file that you always need a set of 5 lines where the first line always begins with 'matched' (or anything you put in the /'s), but the other lines vary. This would be a good way to only grab those sets of lines that you need without having to search through the rest of the logfile.
S.K. Chan
Honored Contributor

Re: perl scripting

What it does (I think) is it'll go through line by line, when it sees the first line that starts with the word "matched" it'll print that line. Subsequently it'll keep printing the next 4 lines (assuming those lines do not start with the word "matched") and ignore the rest until it finds the next line starting with "matched". That will continue until eof. Example ..
logfile
=======
1 hello there
2 matched me
3 noway I am doing this
4 plese let me go
5 jump
6 let me go
7 dont do it
8 matched me number 2
9 hello again
10 matched me number 3
11 noway U are buying this
12 matched
13 no-way I am doing this
14 please let me go
15 jump
16 let me go
17 dont do it
18 matched
19 matched
The output would be lines
2,3,4,5,6,8,9,10,11,12,13,14,15,16,18,19
H.Merijn Brand (procura
Honored Contributor

Re: perl scripting

the last part is not needed, nor are the braces and some line noise

# perl -ne '/^matched/ and$n=5;--$n and print' logfile

does exactly the same. S.K.'s explanation is perfect.

Enjoy, have FUN! H.Merijn

Enjoy, Have FUN! H.Merijn