Awk, text processing

Fooling around with load average output on a shared host (where it can be life-or-death):


$ w -s|awk '/load average:/ { print "Load averages:\nPast 1 min:  " $10 "\nPast 5 min:  " $11 "\nPast 15 min: " $12 }'
Load averages:
Past 1 min:  20.94,
Past 5 min:  20.67,
Past 15 min: 18.75

What’s w, you say? The manpage says:

> w – Show who is logged on and what they are doing.

Awk’s got grep rolled right into it. And the default action is “print the line”. Practical. (Above I had to go all fancy, and adding what those fields mean. Sorry about that. I’m like that.)

If you scroll a bit in the little code window above, you’ll see that the significant values are $10, $11, and $12. The tenth, eleventh, and twelvth *words*! If your data is tab-separated, you change the delimiter to a tab instead. Or, to a comma for CSV files. Bam, you can read almost anything right there.

The concatenation (fancy word for adding two strings to one) sign is… nothing. Elegant.

Read more on awk in [the gawk manual (Free documentation!)](http://www.cs.utah.edu/dept/old/texinfo/gawk/gawk_toc.html).

**Update**: Or, read esr’s [damning of awk](http://www.faqs.org/docs/artu/ch08s02.html#awk), in his [The Art of Unix Programming](http://www.faqs.org/docs/artu/).

Published by olleolleolle

Olle is a programmer, enjoying sunny Malmö in Sweden.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.