如何从文本文件中求和一行数字-Bash Shell脚本 [英] How to sum a row of numbers from text file-- Bash Shell Scripting

查看:136
本文介绍了如何从文本文件中求和一行数字-Bash Shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

行数未知,列数未知.目前,我只是试图用while循环将每一行求和.所需的输出是:

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

要调用该程序,它是stats -r test_file."-r"表示行-我尚未开始输入列.我当前的代码实际上只是获取每列的第一个数字并将它们加在一起,然后将其余的数字作为语法错误输出出去.它说错误来自16之类的错误,它是(((sum = $ sum + $ i))行,但老实说我无法弄清楚问题出在哪里.我应该告诉你,我对bash脚本非常陌生,我已经在Google上搜索了很多内容,但都找不到答案.任何帮助是极大的赞赏.

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.

推荐答案

您正在逐行读取文件,并且求和不是一种算术运算.试试这个:

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

只需使用for循环从每行中拆分每个数字.我希望这会有所帮助.

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

这篇关于如何从文本文件中求和一行数字-Bash Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆