Gawk variables: Difference between revisions

From wikinotes
No edit summary
 
Line 36: Line 36:


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


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


             }
             }
         }'
         }'
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!--  -->
</blockquote><!--  -->

Latest revision as of 17:33, 21 February 2022

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

            }
        }'