sreeja
sreeja

Reputation: 11

Perl one liner to extract and sum numbers from a file

I have a file with data.

File:

Rows: 2
...
...
Rows: 3

The command to search for 'Rows'.

perl -ne 'while (/Rows\:/gi) { s/([.]*Rows :)([.]*)/$2/i, s/^ *//; print }'`

Gives:

2
3

I want to sum up the value and give a result as 5 (2+3).

Please help.

Upvotes: 1

Views: 2205

Answers (1)

perreal
perreal

Reputation: 97948

The -n flag puts the while loop for you, so you don't need to loop:

perl -lne '$s += $1 if /^Rows:\s*(\d+)/; END{print $s}' input

Upvotes: 4

Related Questions