I have a list with 2 columns.
host1 2
host2 33
host2 21
host1 1
I need to calculate the sum for column 2, and get the format like:
host1 3
host2 54
How should I do this? thx
I have a list with 2 columns.
host1 2
host2 33
host2 21
host1 1
I need to calculate the sum for column 2, and get the format like:
host1 3
host2 54
How should I do this? thx
Just use awk:
$ awk '{a[$1]+=$2}END{for(i in a)print i,a[i]}' file
host1 3
host2 54
Explained:
$ awk '{
a[$1] += $2 # Group on column 1 key, and sum column 2 values.
}
END { # When all lines done:
for(i in a) # For each key:
print i, a[i] # Output key and sum.
}' file
bash implementation:
sum() {
# read and accumulate input
declare -A a
while read k v
do
declare -i a["$k"]
a["$k"]+=$v
done
# print accumulated result
for k in "${!a[@]}"
do
echo "$k" ${a["$k"]}
done
}
cat <<EOF | sum
host1 2
host2 33
host2 21
host1 1
EOF
which yield this output:
host1 3
host2 54
Lets say content is in file temp.txt
Solution:
awk '{seen[$1]+=$2;}END{for(indx in seen) print indx" " seen[indx];}' temp.txt
Output:
host1 3
host2 54
Here is how you can add numbers of second column:
numbers=`cat file | cut -f 2 -d " "`
sum=0
for i in $numbers
do
sum=$((sum+i))
done
echo $sum
Cut will get you numbers of second column. You can add these numbers with a for loop. After executing this script you will get
[user@host ~]$ ./shell_name.sh
57