jdamae
jdamae

Reputation: 3909

perl - help parsing out number values from many small text files

I have a number of files in a common directory (/home/test) with a common name:

ABC_1_20110508.out    
ABC_1_20110509.out
ABC_1_20110510.out
..

Each text file has one record that looks like this:

(count, 553076)

I would like to strip out the numbers and just list them out in a file one at a time.

553076
1005
7778000
...

Can someone show me how to do this using perl?

Upvotes: 2

Views: 566

Answers (3)

TLP
TLP

Reputation: 67900

Sounds like a one-liner to me:

$ perl -wne '/(\d+)/ && print "$1\n"' *.out > out.txt

Upvotes: 2

Matt K
Matt K

Reputation: 13842

Easiest way is to use the <> operator. When invoking a perl program without arguments, <> acts just like <STDIN>. If you call it arguments, <> will give you the contents of every file in @ARGV without you having to manually manage the filehandles.

Ex: ./your_script.pl /home/test/ABC_1_????????.out or cat /home/test/ABC_1_????????.out | ./your_script.pl. These would have the same effect.

Upvotes: 0

Nathan Fellman
Nathan Fellman

Reputation: 127428

use this regex:

/\(\w+, (\d+)\)/

you can also use the magic diamond operator to iterate over all of the files at once:

while (<>) {
    # extract the number
    /\(\w+, (\d+)\)/;

    # print it out
    print $1, "\n";

}

And if your perl script is called myscript.pl, the you can call it like this:

$ myscript.pl /home/test/ABC_1_*.out

Upvotes: 3

Related Questions