如何对文本文件中的一行数字求和——Bash Shell Scripting

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33006845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:41:17  来源:igfitidea点击:

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

bashshellsumrows

提问by clb

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:

我正在尝试编写一个 bash 脚本,用于按行和列计算数字的平均值。我正在阅读的文本文件的一个例子是:

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:

行数未知,列数未知。目前,我只是想用一个 while 循环对每一行求和。所需的输出是:

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 < 

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.

要调用程序,它是 stats -r test_file。“-r”表示行——我还没有开始列。我当前的代码实际上只是取每列的第一个数字并将它们加在一起,然后其余的数字作为语法错误出现。它说错误来自像 16,它是 (( sum=$sum+$i )) 行,但老实说,我无法弄清楚问题是什么。我应该告诉你,我对 bash 脚本非常陌生,我在谷歌上搜索并搜索了很多关于这个问题的答案,但找不到。任何帮助是极大的赞赏。

采纳答案by Kadir

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 < 

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

只需使用 for 循环从每一行拆分每个数字。我希望这有帮助。

回答by bufh

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

另一种非 bash 方式(con:OP 要求 bash,pro:不依赖于 bashisms,使用浮动)。

awk '{c=0;for(i=1;i<=NF;++i){c+=$i};print 
while read line
do
    sum=$(sed 's/[ ]\+/+/g' <<< "$line" | bc -q)
    echo "$line Sum = $sum"
done < filename
, "Sum:", c}'

回答by sat

Another way (not a pure bash):

另一种方式(不是纯的bash):

##代码##