I want a bash command that I can pipe into that will sum a column of numbers. I just want a quick one liner that will do something essentially like this:
cat FileWithColumnOfNumbers.txt | sum
“UtilityBills. txt” represents the name of the text file from which we have to read the data. Then we have the “awk” keyword followed by the “sum” expression that will actually calculate the sum from the second column of our dataset, and then the “print” command will be used to display the results on the terminal.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
paste -sd+ infile | bc
<cmd> | paste -sd+ | bc
Edit: With some paste implementations you need to be more explicit when reading from stdin:
<cmd> | paste -sd+ - | bc
Options used:
-s (serial) - merges all the lines into a single line
-d - use a non-default delimiter (the character
+
in this case)
I like the chosen answer. However, it tends to be slower than awk since 2 tools are needed to do the job.
$ wc -l file 49999998 file $ time paste -sd+ file | bc 1448700364 real 1m36.960s user 1m24.515s sys 0m1.772s $ time awk '{s+=$1}END{print s}' file 1448700364 real 0m45.476s user 0m40.756s sys 0m0.287s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With