Gawk variables: Difference between revisions

From wikinotes
No edit summary
 
(2 intermediate revisions by the same user not shown)
Line 13: Line 13:
= Assignment =
= Assignment =
<blockquote>
<blockquote>
<syntaxhighlight lang="bash">
<syntaxhighlight lang="awk">
integer = 1;
integer = 1;
float = 1.1;
float = 1.1;
Line 21: Line 21:
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Assignment -->
</blockquote><!-- Assignment -->
= Assignment Operators =
<blockquote>
<syntaxhighlight lang="awk">
var+= 1;
</syntaxhighlight>
</blockquote><!-- Assignment Operators -->
= Passing Variables to future Iterations =
<blockquote>
You can use the awk process's environment variables to assign a variable in one line, and re-use it on another.<br>
In this example, we capture the name of the <code>vdev</code> and set it in <code>$LAST_VDEV</code> environment variable.<br>
Each mirror now knows which vdev it belongs to.
<syntaxhighlight lang="bash">
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
            }
        }'
</syntaxhighlight>
</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

            }
        }'