How to combine counts in one bash layer

I often use sort | uniq -cto create account statistics. Now, if I have two files with such count statistics, I would like to collect them and add the counts. (I know that I can add source files and count there, but it can be assumed that only count files are available).

For instance:

a.cnt:

   1 a
   2 c

b.cnt:

   2 b
   1 c

I would like to combine and get the following output:

   1 a
   2 b
   3 c

What is the shortest way to do this in a shell?

Edit:

Thanks for the answers so far!

Some possible side aspects that could be considered additionally:

  • what if a, b, c are arbitrary strings containing arbitrary spaces?
  • , , ? sort | uniq -c -style , ?
+5
3

:

$ cat a.cnt b.cnt | awk '{a[$2]+=$1} END{for (i in a) print a[i],i}'
1 a
2 b
3 c

, , , 10 , cat f1 f2 ... awk.

, ( !):

awk '{a[$2]+=$1} END{for (i in a) print a[i],i}' *cnt

, , cnt.


, :

  • a, b, c - , ?
  • , , ? - sort | uniq -c -style , ?

:

awk '{count=$1; $1=""; a[$0]+=count} END{for (i in a) print a[i],i}' *cnt

, sort | uniq -c cnt, . - :

awk '{a[$0]++} END{for (i in a) print a[i], i}' file

Example

$ cat a.cnt
   1 and some
   2 text here

$ cat b.cnt
   4 and some
   4 and other things
   2 text here
   9 blabla

$ cat *cnt | awk '{count=$1; $1=""; a[$0]+=count} END{for (i in a) print a[i],i}'
4  text here
9  blabla
4  and some
4  and other things

:

$ cat b
and some
text here
and some
and other things
text here
blabla

$ awk '{a[$0]++} END{for (i in a) print a[i], i}' b
2 and some
2 text here
1 and other things
1 blabla
+9

awk:

awk 'FNR==NR{a[$2]=$1;next} $2 in a{a[$2]+=$1}1' a.cnt b.cnt
1 a
2 b
3 c
+5
$ awk '{a[$2]+=$1}END{for(i in a){print a[i], i}}' a.cnt b.cnt
1 a
2 b
3 c
+5
source

Source: https://habr.com/ru/post/1531608/


All Articles