DEV Community

Discussion on: One-liner to sum up numbers from a CSV file

Collapse
 
netikras profile image
Darius Juodokas

Single command oneliner :)

awk -F, '{if(NR==1)next;total+=$2}END{print total}' shopping.csv
Enter fullscreen mode Exit fullscreen mode
  • if(NR==1) // if Number_of_Row is 1, i.e. if it's the first row
  • next // continue, i.e. skip the row and go to the next one
  • total+=$2 // create a global variable total if not exists (initialized with '0') and add 2nd column value to it.

Repeat above for all the lines

  • END{print total} // print the global variable total to the console.

I used to hate awk scripts - they are so awkward to read... But awk embeds so many shell utilities that it's really worth to learn it ;)

Collapse
 
netikras profile image
Darius Juodokas

Or a shorter (less verbose) version:

awk -F, 'FNR>1{total+=$2}END{print total}' shopping.csv
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sfkulyk profile image
Sergii Kulyk • Edited
awk -F, '{sum+=$2}END{print sum}' shopping.csv
Enter fullscreen mode Exit fullscreen mode
cut -d, -f2 a.txt|paste -s -d+|bc
Enter fullscreen mode Exit fullscreen mode