Tuesday, February 7, 2012

Adding numbers in a file

If you have a small file filled with numbers and are tasked to add all of them, you can do it with bc and paste:

cronos@olimpo:~$ cat file.txt
1|11
2|22
3|33
4|44
5|55
|
6|66
7|77
8|88
9|99

cronos@olimpo:~$ cat file.txt | cut -d '|' -f 1 | grep -v '^$' | paste -sd '+' - | bc
45

With cut you select the field to sum, with grep you select out empty fields, with paste you add at the end of each line a + sign, and with bc you do the addition.

But if you have a very big file this won't work; you can instead use awk:

cronos@olimpo:~$ cat file.txt | awk 'BEGIN {FS="|";OFMT="%.2f"} {a+=$1;b+=$2} END {print "First field:",a,"Second field:",b}'

First field: 45 Second field: 495

With FS you set the field delimiter and with OFMT you set the number format, in this case two decimal places with no scientific notation. With awk a nice extra is to be able to add two or more columns at the same time.

More information:

Sum of numbers in file - UNIX alternatives

No comments:

Post a Comment