//View Tip #62
Latest tips by RSS
Click here to subscribe
Follow Shell-Fu on Twitter
Click here to follow
Follow Shell-Fu on identi.ca
Click here to follow
Throw this in your command pipeline:

perl -ne '$sum += $_;}{ print "Sum: $sum\n";'

closes the
while ( <> ) {
loop that Perl wraps your code in (because of the
) and opens a new one that will only execute after the while loop has finished. You can use this in lots of Perl one-liner tricks.

For a contrived example, to sum the sizes of files in the current directory (learn the joys of cut(1) first):

ls -l | cut -c 30-42 | perl -ne '$sum += $_;}{ print "Sum: $sum\n";'

cut grabs characters 30-42 from stdin, which happen to coincide with my file size column in ls.

View Comments »


Add your comment

Comments are currently disabled
IMHO the following variant is more beautiful:
ls -l | awk '{s+=$5} END{print s}'

By the way characters 30-42 depend on user name and group ;).
Posted 2008-10-16 14:06:28

Home Latest Browse Top 25 Random Hall Of Fame Contact Submit