Reputation: 19
How to do the sum in individual line in Linux?
I have one file :
Course Name: Math
Credit: 4
12345 1 4 5 1 1 1 1 1 5 10 1 2 2 20
34567 2 3 4 1 10 5 3 2 5 5 10 20 5
Course Name: English
Credit: 4
12345 1 4 5 1 1 1 1 1 5 10 1 20
34567 4 1 10 5 3 2 5 5 10 20 5
Its output will be come:
Course Name: Math
Credit: 4
12345 55
34567 75
Course Name: English
Credit: 4
12345 51
34567 70
I tried this code:
awk '{for (i=2; i<=NF; i++) {tot += $1}; print $1 "\t" tot; tot =0}' file > file2
The output is like this:
Course Name: 0
Credit: 4
12345 55
34567 75
Course Name: 0
Credit: 4
12345 51
34567 70
Actually I need to display a Course name too (Math and English). I am trying to fix it but I couldn't. Can you please help?
Upvotes: 1
Views: 170
Reputation: 58401
This might work for you too!
sed '/:/{s/.*/echo "&"/;b};s/ /+/2g;s/\(\S*\) \(.*\)/echo "\1\t\$((\2))"/' file | sh
Upvotes: 0
Reputation: 246807
Just with the shell
while read line; do
case $line in
Course*|Credit*) echo "$line" ;;
*) set -- $line
id=$1
shift 1
sum=$(IFS=+; echo "$*" | bc)
printf "%s\t%d\n" $id $sum
;;
esac
done < filename
Upvotes: 0
Reputation: 212248
Try:
awk '/^[0-9]/{for (i=2; i<=NF; i++) {tot += $i}; print $1 "\t" tot; tot =0} !/^[0-9]/'
This will only sum lines that start with a digit, and simply print those that don't.
Upvotes: 2