Reputation: 3
I am converting some bash-style (actually using busybox) scripts to c for usage in a custom kernel driver. Everything is going fine but I'm dreadfully unfamiliar with awk, and would really appreciate an explanation of what this one liner is doing. The function is here:
checksum=`echo $sum | busybox awk '{$NF *= -1; print}'`
checksum
and sum
are standard integers that have been accounted for, and can be either positive or negative. I just have no clue what happens when sum is piped into the awk function.
Upvotes: 0
Views: 103
Reputation: 6345
This piece of code awk '{$NF *= -1; print}'
multiplies the value of the last field $NF
by -1
in all the lines and then it prints the whole line with the new value assigned to last field $NF
.
This syntax is often called a shorthand assignment and is equivalent to $NF=$NF*-1
. Similarilly we have more shorthand operations like addition and subtraction:
$ echo "1 2 3" |awk '{$NF *=10;print}' #Equivalent to $NF=$NF*10
1 2 30
$ echo "1 2 3" |awk '{$NF +=10;print}' #Equivalent to $NF=$NF+10
1 2 13
$ echo "1 2 3" |awk '{$NF -=10;print}' #Equivalent to $NF=$NF-10
1 2 -7
$ echo "1 2 3" |awk '{$NF /=10;print}' #Equivalent to $NF=$NF/10
1 2 0.3
In your case:
$ echo "1 2 3" |awk '{$NF *=-1;print}'
1 2 -3
Mind that in awk, each input line - each record, is by default separated by one or more spaces.
Then each line is split into fields starting from $1
(first field) up to the last field $NF
.
$ echo "1 2 3" |awk '{print $1}'
1
$ echo "1 2 3" |awk '{print $2}'
2
$ echo "1 2 3" |awk '{print $3}'
3
$ echo "1 2 3" |awk '{print $NF}'
3
The whole record in awk is called $0:
$ echo "1 2 3" |awk '{print $0}'
1 2 3
A single print, by default prints the whole line $0
:
$ echo "1 2 3" |awk '{print}'
1 2 3
Upvotes: 3