Reputation: 3768
I am having a very basic quarrel with my understanding of awk's way of using variable assignment. In the below how come the output from the variable new
that I assign is not printed - instead the whole record ($0
) get printed. I did look trough the GNU user's guide but failed to comprehend this very fundamental behavior. Thanks for the patience!
echo "a b c" | awk '
{
print $NF #This prints c
new=$NF
print $new #Why does this not print c
}'
Output:
c
a b c
Upvotes: 1
Views: 357
Reputation: 10552
It is tempting to associate the $ with strings, as some languages use this convention. Furthermore, shells such as bash use the $ to retrieve a variable value. And the most confusing thing is, both the shell and awk use $ with a number to parse fields from a complete line. So $1 contains the first field, and so on. But nowhere else do variables in awk use the dollar sign.
Upvotes: 0
Reputation: 5432
You can update the line to print to print new
; Accessing variables is C-type in awk.
new=$NF
is same as:
new=$3
(the value of NF is evaluated to 3)
And now that the variable new
has the value of 3rd column(c
), you can use:
print new
Else, as per @anubhava's answer, you can assign the value of NF
to new
and use it with the $
symbol to print the 3rd column.
Upvotes: 0
Reputation: 784878
To understand difference use this code:
echo "a b c" | awk '
{
print $NF #This prints c
new=NF
print $new #Why does this not print c
}'
Output: It correctly prints:
c
c
When you use new=$NF
instead of new=NF
you assign value of last field into new
. And then when you do $new
again in print
statement then awk
attempts to convert c
to a number and gets 0
hence it prints whole line.
Upvotes: 3