http://qs321.pair.com?node_id=1125793


in reply to Find maximum number in text file and copying its full statement in new text file?

G'day sumathigokul,

Your regex baffles me! You're trying to match (and capture) one or more digits immediately preceded by and followed with a colon — clearly not what you want. I'd recommend spending some time with the Perl Regular Expressions Tutorial.

You have no code to output the wanted lines — which is why that part isn't working. Take a look at open; note how both of the initial examples (for reading and writing) use the 3-argument form and lexical filehandles; start doing this yourself.

This code has the logic you need — you'll need to add the I/O:

#!/usr/bin/env perl use strict; use warnings; my $re = qr{ \A \s+ ( \d+ ) }x; my $high = 0; my @lines; while (<DATA>) { /$re/ or next; my $num = $1; next if $num < $high; if ($num > $high) { $high = $num; @lines = (); } push @lines, $_; } print "Highest number: $high\n"; print @lines; __DATA__ High fanout nets in the post compile netlist: Fanout Type Name -------------------------- 2 INT_NET Net : c_c Driver: c_pad 2 INT_NET Net : b_c Driver: b_pad 2 INT_NET Net : a_c Driver: a_pad 1 INT_NET Net : sum_c Driver: sum_1_SUM0_0 1 INT_NET Net : N_5 Driver: sum_1_CO0_i

Output:

Highest number: 2 2 INT_NET Net : c_c 2 INT_NET Net : b_c 2 INT_NET Net : a_c

-- Ken

Replies are listed 'Best First'.
Re^2: Find maximum number in text file and copying its full statement in new text file?
by sumathigokul (Acolyte) on May 07, 2015 at 05:16 UTC

    Hi kcott,

    First of all thank you for your reply and Good day to you...I have modified the code, so that it extracts the data from one file and copies those statements to new file...But, its not copying...

    use strict; use warnings; my $re = qr{ \A \s+ ( \d+ ) }x; my $high = 0; my @lines; open (F1, "<designer.log") or die ; open (F2, ">>new_lines.txt") or die; while (<F1>) { /$re/ or next; my $num = $1; next if $num < $high; if ($num > $high) { $high = $num; @lines = (); } push @lines, $_; print F2 @lines; } print "Highest number: $high\n"; close (F1); close (F2);

    Correct me if its wrong....

      If you are going to print inside the loop, then use of @lines is useless (given the code), for the current line would be the only one (1) element of @lines, ever.

      What is your input? What is the highest number printed?

        Yeah its is printing as "Highest number:2", but, its not printing to new file.The following is the input file.

        High fanout nets in the post compile netlist: Fanout Type Name -------------------------- 2 INT_NET Net : c_c Driver: c_pad 2 INT_NET Net : b_c Driver: b_pad 2 INT_NET Net : a_c Driver: a_pad 1 INT_NET Net : sum_c Driver: sum_1_SUM0_0 1 INT_NET Net : N_5 Driver: sum_1_CO0_i