简体   繁体   中英

Iterate through a log file and use a regular expression to extract a time value from line

I have a perl script creates a text file, writes captured lines from a garbage collection log to it and saves the file in an archived/timestamped folder. The file will have lines that look like this:

413489.272: [GC [PSYoungGen: 323892K->3126K(332352K)] 623290K->303976K(1031424K), 0.0253970 secs] [Times: user=0.03 sys=0.00, real=0.02 secs]

413503.531: [GC [PSYoungGen: 319094K->7280K(333760K)] 619944K->310249K(1032832K), 0.0614640 secs] [Times: user=0.06 sys=0.00, real=0.06 secs]

413521.441: [GC [PSYoungGen: 324592K->6867K(333056K)] 627561K->310363K(1032128K), 0.0574120 secs] [Times: user=0.06 sys=0.00, real=0.06 secs]

  ... 

What I'd like to do is iterate through these lines in the file, and use a regular expression to get the value of the "real" time (eg real=0.06 secs , but just the 0.06), and store it in a $time variable. I figure a positive lookbehind would work for this, something like /(?<=real=)\\d\\.\\d\\d/ , but that is not working.

In the end my script would look along the lines of:

open LOG,"<","./report/archive/reports-$now/gclog.txt" or die "Unable to read file: $!";
    #while there is lines in the file
        #regex to match time value -> store in variable
        #print variable (just as a check for now)
        #some other stuff not really relevant to this question
close LOG;

I am fairly new to perl, any help would be greatly appreciated!

You don't need the negative look behind, just a capture.

Use:

my ($time) = /\breal=([0-9.]+)/;

The \\b is probably not necessary, but I always prefer to match my word boundaries just in case.

The () cause it to capture the output, which is returned as an array. I, then, put the returned value in the variable named $time . The capture value is also available in $1 , but I prefer to return it this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM