0

I meet a awk array issue, details as below:

[~/temp]$ cat test.txt
1
2
3
4
1
2
3

Then I want to count the frequency of the number.

[~/temp]$ awk 'num[$1]++;END{for (i in num){printf("%s\t%-s\n", num[i],i)|"sort -r -n -k1"} }' test.txt
1
2
3
2       3
2       2
2       1
1       4

As you see, why does the output of first 3 line '1 2 3' will come blank value?

Thank for your answer.

1
  • Did you Google about how can you do it? Commented Nov 12, 2018 at 2:53

2 Answers 2

1

An awk statement consists of a pattern and related action. Omitted pattern matches every record of input. Omitted action is an alias to {print $0}, ie. output the current record, which is what you are getting. Looking at the first part of your program:

$ awk 'num[$1]++' file
1
2
3

Let's change that a bit to understand what happens there:

$ awk '{print "NR:",NR,"num["$1"]++:",num[$1]++}' file
NR: 1 num[1]++: 0
NR: 2 num[2]++: 0
NR: 3 num[3]++: 0
NR: 4 num[4]++: 0
NR: 5 num[1]++: 1
NR: 6 num[2]++: 1
NR: 7 num[3]++: 1

Since you are using postfix operator num[$1]++ in the pattern, on records 1-4 it gets evaluated to 0 before it's value is incremented. Output would be different if you used the prefix operator ++num[$1] which would first increment the value of the variable after which it would get evaluated and would lead to outputing every record of input, not just the last three, which you were getting.

Correct way would've been to use num[$1]++ as an action, not as a pattern:

$ awk '{num[$1]++}' file
Sign up to request clarification or add additional context in comments.

1 Comment

really appreciate~
0

Put your "per line" part in {} i.e. { num[$1]++; }

awk programs a a collection of [pattern] { actions } (the pattern is optional, the {} is not). Seems that in your case your line is being treated as the pattern.

1 Comment

yes, you are right , but how to explain the command when missing { } , I want to know it more about the significance of { } in awk.

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.