Gawk variables: Difference between revisions
From wikinotes
No edit summary |
No edit summary |
||
Line 28: | Line 28: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Assignment Operators --> | </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"> | |||
zpool status $pool \ | |||
| awk '/^config:/,/end/ { print $0 }' \ | |||
| awk '/[ \t]+zroot/,/^$/ | |||
{ | |||
indent=match($0, "\t"); | |||
if (length($indent) == 8) { | |||
ENVIRON["LAST_VDEV"]=$1; | |||
} else if (length($indent) == 6) { | |||
print "vdev="ENVIRON["LAST_VDEV"]",partition="$1",state="$2 | |||
} | |||
}' | |||
</syntaxhighlight> | |||
</blockquote><!-- --> |
Revision as of 16:59, 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 thevdev
and set it in$LAST_VDEV
environment variable.
Each mirror now knows which vdev it belongs to.zpool status $pool \ | awk '/^config:/,/end/ { print $0 }' \ | awk '/[ \t]+zroot/,/^$/ { indent=match($0, "\t"); if (length($indent) == 8) { ENVIRON["LAST_VDEV"]=$1; } else if (length($indent) == 6) { print "vdev="ENVIRON["LAST_VDEV"]",partition="$1",state="$2 } }'