Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Awk access variable more than once

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading