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?
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.