2

How can I find the sum of this column from a file named cars?

73
60
45
102
15
50
115
30
10
180
85
25

How can I add these numbers up (using the command line)? I showed this list typing

awk '{ print $4 }' cars
kvantour
  • 25,269
  • 4
  • 47
  • 72
Sleever
  • 47
  • 4

3 Answers3

3

Given:

$ cat file
73
60
45
102
15
50
115
30
10
180
85
25

You can do:

$ paste -sd+ file | bc
790

Or, given a multi column file:

$ cat file
0   73  1
2   60  3
4   45  5
6   102 7
8   15  8
9   50  10
11  115 12
13  30  14
15  10  16
17  180 18
19  85  20
21  25  22

You can use cut to get the column of interest:

$ cut -f 2 file | paste -sd+ - | bc
790
dawg
  • 98,345
  • 23
  • 131
  • 206
0

1st Solution in awk: Could you please try following once.(I am taking sum of column 4 since your attempt shows it, had written a dynamic command where you need to change only variable's value and it will take that column's SUM then)

awk -v column_number=4 '{sum+=$column_number} END{print "SUM of column " column_number " is: " sum}'  Input_file

By running above code you could give any column number in variable column_number and could take some of it. In case you have any other requirement then kindly do show us sample input and expected sample output in code tags in your post.

Explanation of above code:

awk -v column_number=4 '    ##Starting awk program here and setting variable column_number value to 4 you could change it as per your column number too, for which you want to take SUM for all lines of Input_file.
{                           ##Starting a BLOCK here.
  sum+=$column_number       ##Creating a variable named SUM whose value is value of current lines $column_number value and it keep adding SUMs value to its own to get cumulative sum of all columns in all lines.
}                           ##Closing BLOCK here.
END{                        ##Mentioning awk program END block here, it will be executed when an Input_file is being done with reading.
  print "SUM of column " column_number " of all lines in Input_file is: " sum     ##Printing SUM variable value here.
}'  Input_file              ##Mentioning Input_file name here.

2nd Solution in bash: Considering that your lines in Input_file have only 1 entry.

while read line; do    sum=$(($sum+$line)) ; done < "Input_file"; echo "$sum"
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
0

Here is a way to do it on command line, but not awk.

vim /tmp/text
let sum=0
for X in `cat /tmp/text`; do let sum=$sum+$X; done
echo $sum
Jose Martinez
  • 11,452
  • 7
  • 53
  • 68
  • though I have not given down vote here. IMHO you need not to read Input_file in every iteration of `for` loop you could see this link where we could use loop in bash to get sum once too https://stackoverflow.com/a/53688677/5866580 – RavinderSingh13 Dec 09 '18 at 01:53