Gawk variables

From wikinotes
Revision as of 17:33, 21 February 2022 by Will (talk | contribs) (→‎Passing Variables to future Iterations)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Arguments

Arguments are named like in bash, $1 for the first, $2 for the second, etc.
$0 refers to the entire line.

echo "foo" "bar" | awk 'BEGIN { print $1 $2 }'  # foobar

awk -f file.awk "foo" "bar"                     # akw scripts

Assignment

integer = 1;
float = 1.1;
string = "abc";
array[1] = "abc";
result = ( (1/100) * 20 );

Assignment Operators

var+= 1;

Passing Variables to future Iterations

You can use the awk process's environment variables to assign a variable in one line, and re-use it on another.
In this example, we capture the name of the vdev and set it in $LAST_VDEV environment variable.
Each mirror now knows which vdev it belongs to.

pool=zroot
zpool status $pool  \
    | awk '/^config:/,/end/ { print $0 }' \
    | awk '/[ ]+'"$pool"'/,/^$/
        {
            match($0, /^[ \t]+/);  # sets RLENGTH (match length)
            if (RLENGTH == 3) {
                ENVIRON["LAST_VDEV"]=$1;

            } else if (RLENGTH == 5) {
                print "vdev="ENVIRON["LAST_VDEV"]",partition="$1",state="$2

            }
        }'