2

I have data that need to be count how many occurrences.

1
2
1
2
3
1

And used the awk command below and work properly.

awk -F'","' '{ a[$1]++ } END { for (n in a) print n "=" a[n] } ' text.txt

And the output:

2=2
3=1
1=3

The other problem is it needs to count how many stored in array. The expectation is I need also to count or number of lines from the output above. Expected Output: 3

  • need to be awk ? Much easier using right tools for this, e.g. ... | sort | uniq -c – pLumo May 22 at 11:38
  • yes. trying to build from .awk script stand alone. Since there are other processing of data. – Robert Jhay Lumayag May 22 at 11:58
2

Use the command

awk '{a[$1]++}  END { for ( n in a ) { i++; print n "=" a[n]} print i }' file

E.g.


#!/bin/bash
echo '1
2
1
4
5
4' | awk '{a[$1]++}  END { for ( n in a ) { i++; print n "=" a[n]} print i }'

Output will be

1=2
2=1
4=2
5=1
4
  • Thanks a lot. I already integrated to my .awk script and work properly. thanks! – Robert Jhay Lumayag May 22 at 11:58
3

In GNU awk, length(my_arry) will display the number of elements your associated my_arry has taken.

in other implementations that doesn't support array length, you can do:

awk '{ … } END{ for (elements in my_arry) count++; print count }'
-1

Done by below method

command:awk '{a[$1]++}END{for(x in a)print a[x]"="x}' filename

command: @praveen:~$ awk '{a[$1]++}END{for(x in a)print a[x]"="x}' p.txt
3=1
2=2
1=3
praveen@praveen:~$
  • This is just the code from the question, with trivial / cosmetic changes.  This makes no attempt to answer the question. – Scott Jun 21 at 5:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.