I am trying to access a variable defined in awk multiple times, but it does not seem to work.
Lets assume we have a data.txt
with contents:
1 2
2 3
3 4
If we do awk with:
cat data.txt | awk 'sum=($1+$2), div1=(sum/$1) {print " sum: " sum " div1: " div1 " data: " $0}'
It works fine and we get an output of
sum: 3 div1: 3 data: 1 2
sum: 5 div1: 2.5 data: 2 3
sum: 7 div1: 2.33333 data: 3 4
If I try to access the sum
multiple times, I get an error
cat data.txt | awk 'sum=($1+$2), div1=(sum/$1), div2=(sum/$2) {print " sum: " sum " div1: " div1 " div2: " div2 " data: " $0}'
Even if I change div2=(sum/$2)
to div1=(sum/$1)
, which is exactly the same as before, I will still get the error:
awk: line 1: syntax error at or near ,
How can I get around this issue and access any specific variable assigned in awk to be accessible multiple times?
>Solution :
The part before the {}
block is supposed to be a condition. Put variable assignments inside the {}
. Multiple statements are separated using ;
.
cat data.txt | awk '{sum=($1+$2); div1=(sum/$1); div2=(sum/$2); print " sum: " sum " div1: " div1 " div2: " div2 " data: " $0}'