4
votes

I'm trying to parse a file in perl. I want to print all lines after the regex match

For example, the file is

num_of_dogs,10,#start_reading
num_of_cat,15
num_birds,20
num_of_butterfly,80
.....

I want all the lines after the match #start_reading

I've tried this, but it just prints next line

while (my $line = <$csv_file>) {
    next unless $line =~ /(.*),#end_of_tc/;
    if ($line =~ /(.*)/){
    print $file = $1;
    }
}

The output would look like this

num_of_cats,15
num_of_birds,20
......

Thanks in advance

4
Can you show what the input file looks like by editing your post ? - m.raynal

4 Answers

7
votes

You may also use the flip-flop, (..) operator to bypass all the lines from the beginning of the file to the one containing #start_reading

while (<$fh>) {
    next if 1 .. /#start_reading/;
    print;
}

This bypasses the print from line 1 of the file to the line matching #start_reading. Then it prints the remaining lines in the file.

7
votes

You can set a flag when the line contains #start_reading and only print the line if the flag is true:

while (my $line = <$csv_file>) {
    print $line if $start;
    $start ||= $line =~ /#start_reading/;
}

And if you want to stop reading after encountering #stop_reading:

while (my $line = <$csv_file>) {
    print $line if $print;
    $print ||= $line =~ /#start_reading/;
    $print &&= $line !~ /#stop_reading/;
}
3
votes
 perl -ne 's/.+\,#start_reading\s*/next/e; print $_' d

by gnu sed, if your data in 'd',

 sed -En '/.+,#start_reading/{:s n; $q;p; bs }' d
3
votes

An efficient and clean way to process a file only after a certain point

last if /#start_reading/ while <$csv_file>;  # get past that point in file

while (<$csv_file>) { print }                # now work on it