2

I am trying to use awk as some types of element counter as follows, but I got syntax error.

cat file | awk '{if($2>$3)A[$1]++}END{for(index in A){print index, A[index]}}'

Can someone help?

Here is the syntax error:

awk: {if($2>$3)A[$1]++}END{for(index in A){print index, A[index]}}
awk:                                 ^ syntax error
awk: {if($2>$3)A[$1]++}END{for(index in A){print index, A[index]}}
awk:                                                  ^ syntax error
awk: {if($2>$3)A[$1]++}END{for(index in A){print index, A[index]}}
awk:                                                           ^ syntax error

Thanks you very much!

2 Answers 2

3

It appears that index is a reserved word. Change it to something else. Perhaps key.

Sign up to request clarification or add additional context in comments.

Comments

1

Good Practices:

  1. As Kevin pointed out, index is a reserved word. Try using a different key for your array subscripts.

  2. Useless use of cat. awk can take filename as an input. Do something like this -

    awk '{if($2>$3)A[$1]++}END{for(i in A){print i, A[i]}}' file

  3. If $2>$3 is the only condition then you can shorten it to something like following -

    awk '$2>$3{A[$1]++}END{for(i in A){print i, A[i]}}' file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.