如何使用bash将两个数字相加

dot*_*dot 1 bash shell-script

我有以下文件:

lab1:/etc/scripts# cat /tmp/tmp.PGikhA/audit.txt                                
   344 server1                                                                            
     1 server2
Run Code Online (Sandbox Code Playgroud)

我希望能够将每一行的数字相加 - 所以在这种情况下,我想添加 344 + 1 并最终得到 345。

到目前为止,我已经弄清楚了以下步骤:

lab-1:/etc/scripts# cat /tmp/tmp.PGikhA/audit.txt |awk '{print $1}'              
344                                                                                                    
1                     
Run Code Online (Sandbox Code Playgroud)

但我不知道如何将它们加在一起。我知道我可以只使用 $a + $b 语法,但是如何将 344 和 1 放入单独的变量中来做到这一点?

谢谢。

编辑 1

我得到了两个返回的值,而不仅仅是一个。看不出我做错了什么:

lab-1:/etc/scripts# cat /tmp/tmp.jcbiih/audit.txt | awk '{print $1}' | awk '{ sum+=$1} {print      
sum}'                                                                                                                    
344                                                                                                                      
345                                                                                                                      
lab-1:/etc/scripts# cat /tmp/tmp.jcbiih/audit.txt  | awk '{ sum+=$1} {print sum}'                  
344                                                                                                                      
345                                                                                                                      
Run Code Online (Sandbox Code Playgroud)

jor*_*anm 5

您可以轻松地在 awk 中进行数学运算。下面是一个例子:

awk '{ total+=$1 } END { print total }'
Run Code Online (Sandbox Code Playgroud)

如果你真的想使用 bash,你可以使用一个简单的循环一次读取一行并将其相加:

count=0 
while read -r number _; do # put the first column in "number" and discard the rest of the line
    count=$(( count + number )) 
done < /tmp/foo
echo $count
Run Code Online (Sandbox Code Playgroud)

  • @dot 你离开了“END”,它告诉 awk 在完成处理所有数据之前不要打印。 (2认同)