Find the line and add if it matches
I have a file that has 2 columns as below.
101 6
102 23
103 45
109 36
101 42
108 21
102 24
109 67
etc.
I want to write a script that adds values from the second column if their corresponding first column matches
for example add all 2nd column values if it 1st column is 101
add all 2nd column values if it 1st colummn is 102
add all 2nd column values if it 1st colummn is 103 and so on ...
I wrote my script like this but I am not getting the correct result
awk '{print $1}' data.txt > col1.txt
while read line
do
awk ' if [$1 == $line] sum+=$2; END {print "Sum for time stamp", $line"=", sum}; sum=0' data.txt
done < col1.txt
+2
a source to share
2 answers