How to count the number of lines on a single line in Linux bash
I have a file like this:
id|domain
9930|googspf.biz
9930|googspf.biz
9930|googspf.biz
9931|googspf.biz
9931|googspf.biz
9931|googspf.biz
9931|googspf.biz
9931|googspf.biz
9942|googspf.biz
And I would like to count the number of times that a separate id is displayed in my data as shown below:
9930|3
9931|5
9942|1
How can I do this using linux bash? I am currently using this, but I am counting on all lines:
cat filename | grep 'googspf.biz'| sort -t'|' -k1,1 | wc
Can any organ help?
source to share
I first thought about using uniq -c
( -c
for counting) since your data is sorted:
~$ grep "googspf.biz" f | cut -d'|' -f1|uniq -c
3 9930
5 9931
1 9942
And in order to format accordingly, I had to use awk:
~$ grep "googspf.biz" f | cut -d'|' -f1|uniq -c|awk '{print $2"|"$1}'
9930|3
9931|5
9942|1
But then, only with awk:
~$ awk -F'|' '/googspf/{a[$1]++}END{for (i in a){print i"|"a[i]}}' f
9930|3
9931|5
9942|1
-F'|'
use |
as separator, and if the line matches googspf
(or NR>1
: if the line number> 1), then the counter for the first field is incremented. At the end, type accordingly.
source to share