Subscribe / Unsubscribe Enewsletters | Login | Register

Pencil Banner

Doing math with awk

Sandra Henry-Stocker | Aug. 24, 2015
I use awk all the time, but generally only to conveniently pull a particular field out of data that I'm workin with. Regardless of the separator used, awk makes it easy to extract just what you need. But there's a lot more to the language than this obvious feature.

Finally, here's an implementation of the "maybe" command that some Unix folks were laughing about some years ago. The maybe command will vary from "yes" to "no". This implementation is done with an awk command. It will randomly respond with a "yes" or a "no" -- kind of the equivalent of tossing a coin.

#!/bin/bash

ans=`awk -vmin=0 -vmax=1 'BEGIN{srand(); print int(min+rand()*(max-min+1))}'`

if [ $ans -eq 0 ]; then
    echo "no"
else
    echo "yes"
fi

The book "sed & awk" was one of the first O'Reilly books I ever read and these tools played a key role in drawing me into the Unix world decades ago. But awk is more fully functional than I sometimes remember. I get too used to just using it to selecting columns from arbitrary data and forget sometimes how much processing it can do on its own.

 

Previous Page  1  2 

Sign up for CIO Asia eNewsletters.