Skip to content

Instantly share code, notes, and snippets.

@shrayasr
Last active August 29, 2015 14:16
Show Gist options
  • Save shrayasr/b458c66ff77d002fc2cd to your computer and use it in GitHub Desktop.
Save shrayasr/b458c66ff77d002fc2cd to your computer and use it in GitHub Desktop.
Summing a list of numbers from within a file using the shell

File containing numbers

Andaman Nicobar,25
Andhra Pradesh,3550
Arunachal Pradesh,37
Assam,616
Bihar,1777
Chandigarh,32
Chhattisgarh,313
Dadra & Nagar Haveli,3
Daman &,Diu 3
Delhi,408
Goa,90
Gujarat,1896
Haryana,728
Himachal Pradesh,467
Jammu & Kashmir,370
Jharkhand,489
Karnataka,3204
Kerala,4684
Lakshdweep,5
Madhya Pradesh,1154
Maharashtra,6446
Manipur,51
Meghalaya,61
Mizoram,37
Nagaland,44
Orissa,1432
Pondicherry,40
Punjab,812
Rajasthan,2009
Sikkim,32
Tamil Nadu,3784
Tripura,98
Uttar Pradesh,2576
Uttaranchal,359
West Bengal,2100

Command

$ cat pincodes | sort -r -n -k 2 -t "," | awk -F, '{s+=$2} END {print s}'
39729

sort -r -n -k2 -t ","

  • Run the sort command.
  • Show me the output in reverse order with -r
  • It is a numerical sort -n
  • Use the 2nd column as the key -k2
  • Use comma as the separator -t ","

awk -F, '{s+=$2} END {print $s}'

  • Run the awk command
  • The field separator is , -F,
  • Sum the 2nd column into s {s+=$2}
  • At the end END
  • Print s {print s}

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment