Adding numbers matching with words

Hi All,

I have a file which looks like this:

abc 1
abc 2
abc 3
abc 4
abc 5
bcd 1
bcd 3
bcd 3
bcd 5
cde 7

This file is just a miniature version of what I really have. Original file is some 1 million lines long.

I have tried to come up with the code for what I wish to accomplish but to no avail.

The task: What I want to do is the read this file (filename: log.txt) and add all those numbers which correspond to the same word and hence shrink the file to an output file say output_log.txt. I mean this is what I want:

abc 15
bcd 12
cde 7

What I have done is that added all the numbers which appear against the same word that is why I have put 15 against abc that is (1+2+3+4+5=15)

I know how to add the numbers of a coloumn using this

more log.txt | awk '{sum+=$1} END {print sum}'

But I am not able to figure out as to how to shrink the file and put the numbers against them. I am using Linux with BASH.

---------- Post updated at 12:22 PM ---------- Previous update was at 12:14 PM ----------

Great..

I could figure it out after reading some of the posts in this forum:

Here's my code

awk ' {arr[$1]+=$2}  END{for (i in arr){print i, arr }}' log.txt > output_log.txt
#!/bin/bash
for i in `cat inputfile | awk '{print $1 | "uniq"}'`
do
        grep $i inputfile > log.txt
        echo "$i : `awk '{sum+=$2} END {print sum}' log.txt`"
done
1 Like