fork download
  1. #!/usr/bin/env bash
  2.  
  3. target="id" # the field you want to sum
  4. target_idx= # the column number of that field
  5. sum=0 # the sum that wal found so far
  6.  
  7. {
  8. # first, just read the header...
  9. IFS=, read -r -a header
  10. for idx in "${!header[@]}"; do # and look for the id field in it
  11. [[ ${header[$idx]} = $target ]] && { target_idx=$idx; break; }
  12. done
  13. [[ $target_idx ]] || { echo "ERROR: No $target field found" >&2; exit 1; }
  14.  
  15. # then, iterate over other lines
  16. while IFS=, read -r -a line; do
  17. sum=$(( sum + ${line[$target_idx]} ))
  18. done
  19. }
  20.  
  21. echo "$sum"
  22.  
Success #stdin #stdout 0s 19640KB
stdin
id,name
10,abc
20,xyz
30,def
stdout
60