开发者

search for a string , and add if it matches

开发者 https://www.devze.com 2022-12-29 07:18 出处:网络
I have a file that has 2 columns as given below.... 1016 10223 10345 10936 10142 10821 10224 10967 and so on......

I have a file that has 2 columns as given below....

101   6
102   23
103   45
109   36
101   42
108   21
102   24
109   67

and so on......

I want to write开发者_C百科 a script that adds the values from 2nd column if their corresponding first column matches

for example add all 2nd column values if it's 1st column is 101
add all 2nd column values if it's 1st colummn is 102
add all 2nd column values if it's 1st colummn is 103 and so on ...

i wrote my script like this , but i'm 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


awk '{array[$1]+=$2} END { for (i in array) {print "Sum for time stamp",i,"=", array[i]}}' data.txt


Pure Bash :

declare -a sum
while read -a line ; do
  (( sum[${line[0]}] += line[1] ))
done < "$infile"

for index in ${!sum[@]}; do
  echo -e "$index ${sum[$index]}"
done

The output:

101 48
102 47
103 45
108 21
109 103
0

精彩评论

暂无评论...
验证码 换一张
取 消