Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: How to parse this file

by GrandFather (Cardinal)
on Oct 19, 2011 at 21:15 UTC ( #932509=note: print w/ replies, xml ) Need Help??


in reply to How to parse this file

Perl is tuned for parsing. To solve your problem you need to split each line into portions, throw away unwanted stuff, then join the remaining portions together again and print them. Consider:

use warnings; use strict; die <<HELP if ! @ARGV; parse.pl <infile name> <infile name> source file to be processed Output is printed to stdout HELP while (<>) { chomp; print join ' ', grep {/^[+-]?\d+(\.\d*)?$/} split; print "\n"; }

given your sample data in a file passed on the command line prints:

1 1549367 11 8 3 11 0 -12.00 6.00 -0.25 -3.00 0.00 -1.67 -12.00 6.00 - +0.64 1 1549501 15 12 3 3 12 -17.00 6.00 0.50 1.00 6.00 2.67 -17.00 6.00 0.9 +3 1 1549552 14 11 3 6 8 -31.00 6.00 -2.09 -12.00 3.00 -5.67 -31.00 6.00 +-2.86 1 1549563 14 9 5 5 9 -7.00 6.00 0.22 -64.00 4.00 -18.40 -64.00 6.00 -6 +.43 1 1549726 14 13 1 8 6 -3.00 6.00 1.92 6.00 6.00 6.00 -3.00 6.00 2.21 2 1549737 16 15 11 16 10 -64.00 6.00 -35.67 -64.00 6.00 -46.18 -64.00 +6.00 -40.12 2 1549815 9 7 2 8 1 -3.00 6.00 -0.14 -9.00 0.00 -4.50 -9.00 6.00 -1.11 1 1549914 12 11 1 9 3 -9.00 6.00 1.18 -4.00 -4.00 -4.00 -9.00 6.00 0.7 +5 1 1550018

There are a number of important parts there: split, grep, the regular expression in the grep (see perlretut) and join. I strongly recommend that you read the documentation for each of those.

The other bit of magic is <> which reads a line at a time from stdin if there are no command line arguments, or from the files whose names are passed on the command line. Actually without the "helpfull" die the script is even more useful because it can be used as a filter accepting piped input on stdin, or by taking a file (or list of files) on the command line.

True laziness is hard work


Comment on Re: How to parse this file
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://932509]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (6)
As of 2014-12-27 20:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls