-1

I have a delimited text file like this

Code|Grade_CD|FCST|Change_Prob|target
11245|yyy|2020-01-01|25.0124|2020
11245|yyy|2020-01-01|25.0124|2020
11245|yyy|2020-01-01|22.0124|2020
11245|yyy|2020-01-01|22.0124|2020

I need to add all the values under the column "Change_Prob" by ignoring the header in the file and print the sum as Total change_Prob = 94.0496

2
awk -F\| 'NR>1 { sum=sum+$4; }; END { print sum; }' input
| improve this answer | |
1
awk -F'|' 'NR > 1 { sum = sum + $4 }; END { print "Total change_Prob = " sum }' infile
| improve this answer | |
0
{
  col='Change_Prob' 
  printf 'Total %s = ' "$col"
  c=$(head -n 1 | tr '|' '\n' | grep -nxF -- "$col" | cut -d: -f1)
  cut -d"|" -f"$c" - | paste -sd+ | bc -l
} < file
Total Change_Prob = 94.0496

Or if we already know the 4th column has the data then we could also do this:

$ printf 'Total Change_Prob = '
$ tail -n+2 inp | cut -d"|" -f4 - |  tr :- :_ |
   dc -e '[pq]sq[?z1=q+l?x]s?czdd=?'
Total Change_Prob = 94.0496
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.