I have file as the following file on rhel 7.2 machine
more file.txt
car12
car55
car87
car12
car98
car55
car12
car12
car55
car65
car12
car65
we want to sum the words in the file with the quantity as the follwing expected results
car12 - 5
car55 - 3
car87 - 1
car98 - 1
car65 - 2
how to sum the above words with their quantity with awk ?
You don't really need awk for this, you can simply do:
$ sort file | uniq -c
5 car12
3 car55
2 car65
1 car87
1 car98
But yes, it is possible in awk also:
$ awk '{a[$1]++}END{for(word in a){print word" - "a[word]}}' file
car55 - 3
car65 - 2
car87 - 1
car12 - 5
car98 - 1
With GNU awk (gawk
), one may even use a few predefined sortings regarding how the array is traversed, and by extension how it is printed. If you use PROCINFO["sorted_in"]="@ind_str_asc"
, that will cause the results to be printed in the order from most seen to least:
$ awk '{a[$1]++}
END {
PROCINFO["sorted_in"]="@ind_str_asc";
for(word in a){print word" - "a[word]}
}' file
car12 - 5
car55 - 3
car65 - 2
car87 - 1
car98 - 1
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments