Search code examples
sortingawkscriptinguniq

Adding numbers present in similar-lines of file in bash


I have file like this:

[host]$ cat /tmp/data
Breakfast 1
Lunch 1
Dinner 1
Dinner 1
Dinner 1
Lunch 1
Lunch 1
Dinner 1

I want output like:

Breakfast 1
Lunch 3
Dinner 4

How can I do it using command-line scripting awk/sed?

After doing following command I got:

[host]$ cat /tmp/data | sort | tr " " "\n"
Breakfast
1
Dinner
1
Dinner
1
Dinner
1
Dinner
1
Lunch
1
Lunch
1
Lunch
1

I am stuck at how to add these numbers now.


Solution

  • awk '{a[$1]+=$2} END{for(i in a){print i, a[i]}}' /tmp/data
    Dinner 4
    Breakfast 1
    Lunch 3