0

Is there an easy way to find the sum of the values in the first column?

My command line

If so, would this method be different from sum the column in a text file? So the first would be mathematics on command line outputs, and second would be in text files w/o opening them.

Something tells me I might need awk.

Doug
  • 597
  • 2
  • 7
  • 22
  • 2
    The last line of output from `wc` already contains the `total`. So `wc whatever | tail -n 1` trivially solves the stated problem. – tripleee Mar 25 '15 at 10:38

1 Answers1

0

You can use awk to perform operations on standard input or a file. To find the sum of the first column in the output of wc, by piping the result to awk:

wc *.txt | awk '{sum+=$1}END{print sum}'

To find the sum of the first column in a file, by reading the file directly:

awk '{sum+=$1}END{print sum}' file

The awk code is simple - for every line of input, add the value of the first field so the variable sum. Once all of the input has been read, print the value of sum.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • great, thank you. What about about sort files according to these columns – Doug Mar 25 '15 at 08:39
  • @Doug that's a completely separate question, which is already answered elsewhere, e.g. http://stackoverflow.com/q/4262650/2088135 – Tom Fenech Mar 25 '15 at 08:42
  • @TomFenech sum of a column is also answered elsewhere e.g [here](http://stackoverflow.com/questions/29240782/print-sum-of-each-column-with-awk),[here](http://stackoverflow.com/questions/28905083/how-to-sum-a-column-in-awk),[here](http://stackoverflow.com/questions/28445020/summing-values-of-a-column-using-awk-command),etc –  Mar 25 '15 at 09:27
  • @JID you're right, I've voted to close as a duplicate. – Tom Fenech Mar 25 '15 at 09:30