Please how can I count the list of numbers in a file
awk '{for(i=1;i<=NF;i ){if($i>=0 && $i<=25){print $i}}}'
Using the command above I can display the range of numbers on the terminal but if there are so many it will be difficult to count them. Please how can I show the count of the numbers on the terminal for example
1-20,
2-22,
3-23,
4-24,
etc
I know I can use wc
but I don't know how to infuse it into the command above
CodePudding user response:
Pipe the output to sort -n
and uniq -c
awk '{for(i=1;i<=NF;i ){if($i>=0 && $i<=25){print $i}}}' filename | sort -n | uniq -c
You need to sort first because uniq
requires all the same elements to be consecutive.
CodePudding user response:
While I'm personally an awk fan, you might be glad to learn about grep -o
functionality. I'm using grep -o
to match all numbers in the file, and then awk can be used to pick all the numbers between 0 and 25 (inclusive). Last, we can use sort and uniq to count the results.
grep -o "[0-9][0-9]*" file | awk ' $1 >= 0 && $1 <= 25 ' | sort -n | uniq -c
Of course, you could do the counting in awk with an associative array as Ed Morton suggests:
egrep -o "\d " file | awk ' $1 >= 0 && $1 <= 25 ' | awk 'cnt[$1] END { for (i in cnt) printf("%s-%s\n", i,cnt[i] ) } '
I modified Ed's code (typically not a good idea - I've been reading his code for years now) to show a modular approach - an awk script for filtering numbers in the range of 0 and 25 and another awk script for counting a list (of anything).
I also provided another subtle difference from my first script with egrep instead of grep.
To be honest, the second awk script generates some unexpected output, but I wanted to share an example of a more general approach.
CodePudding user response:
awk '
{ for(i=1;i<=NF;i ) if (0<=$i && $i<=25) cnts[$i] }
END { for (n in cnts) print n, cnts[n] }
' file