How to sum a row of numbers from text file— Bash Shell Scripting

ぐ巨炮叔叔 提交于 2019-12-11 04:27:41

问题


I'm trying to write a bash script that calculates the average of numbers by rows and columns. An example of a text file that I'm reading in is:

1 2 3 4 5
4 6 7 8 0

There is an unknown number of rows and unknown number of columns. Currently, I'm just trying to sum each row with a while loop. The desired output is:

1 2 3 4 5 Sum = 15
4 6 7 8 0 Sum = 25

And so on and so forth with each row. Currently this is the code I have:

while read i
do
  echo "num: $i"
  (( sum=$sum+$i ))
  echo "sum: $sum"
done < $2

To call the program it's stats -r test_file. "-r" indicates rows--I haven't started columns quite yet. My current code actually just takes the first number of each column and adds them together and then the rest of the numbers error out as a syntax error. It says the error comes from like 16, which is the (( sum=$sum+$i )) line but I honestly can't figure out what the problem is. I should tell you I'm extremely new to bash scripting and I have googled and searched high and low for the answer for this and can't find it. Any help is greatly appreciated.


回答1:


You are reading the file line by line, and summing line is not an arithmetic operation. Try this:

while read i
do
  sum=0
  for num in $i
  do
    sum=$(($sum + $num))
  done
  echo "$i Sum: $sum"
done < $2

just split each number from every line using for loop. I hope this helps.




回答2:


Another non bash way (con: OP asked for bash, pro: does not depend on bashisms, works with floats).

awk '{c=0;for(i=1;i<=NF;++i){c+=$i};print $0, "Sum:", c}'



回答3:


Another way (not a pure bash):

while read line
do
    sum=$(sed 's/[ ]\+/+/g' <<< "$line" | bc -q)
    echo "$line Sum = $sum"
done < filename


来源:https://stackoverflow.com/questions/33006845/how-to-sum-a-row-of-numbers-from-text-file-bash-shell-scripting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!