0

I have a file with a lot of rows and they all numbers, and i want to add them and get the total of them all, then i'll put it in a loop so it will do this math all the time supplying the result number of all these rows,, i couldn't do this in bash. This example say i'll run this on 100 different servers and i want to add each line in this somefile to the second one and on, on .

Ex:

netstat -ant | grep -c :80 > /path/to/somefile

Is there a way for this in bash or Python ?

lORD
  • 17
  • 5
  • 1
    Can you expand a bit on what your input file looks like? Do you only want to sum the (single column?) row values in each file? – Brandon Deo Jan 13 '16 at 23:52

3 Answers3

0

Here's a bash script

sum=0;
while read p; do
  sum=$(($sum + $p));
done <yourfile.txt

echo $sum
Jamie
  • 2,181
  • 1
  • 21
  • 35
0

In python, string operations are easy. However, a little info is needed.

  • What are the types of the numbers? (int, float, etc)
  • What are separating the numbers? (commas, tabs, spaces)

The general form is something like:

while (1)
sum = 0
with open /path/to/somefile as f:
 for line in f:
  sum_list = (line.split('number_separator')
   for entry in sum_list:
    sum += number_type(entry)

Now, sum will be the sum of the file. What you choose to do with it is up to you.

Owen Hempel
  • 434
  • 2
  • 8
  • Thank you for this ,, it's all int like : 123123 12312 45645 – lORD Jan 15 '16 at 04:24
  • So your separator is ' ' (space character) and your number types are int. Just stick that in the code above I gave you and it should work! You will want to avoid the while (1) loop though, and supply a list of files instead – Owen Hempel Jan 15 '16 at 23:03
0

In awk:

awk '{ sum += $1 } END { print sum }' somefile
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116