如何在 bash 中添加一个带有整数的字符串?

How can i add a string with an integer in bash?

我想读取一个随机文本,其中包含一些随机整数,格式如下:

2:10

4:4

10:15

22:5

然后我想求出每一列的总和。首先,我想拆分每一行,就像每一行都是一个字符串一样:

columnA="$(cut -d':' -f1 <<<$line)"
columnB="$(cut -d':' -f2 <<<$line)"

columnA 包含第一列的元素,columnB 包含第二列的元素。然后我创建了一个变量 sumA=0 并尝试像这样计算每列的总和:

sumA=$((columnA+sumA))

我得到了我想要的结果,但也收到了这条消息

") 语法错误:需要操作数(错误标记为“

第二列相同:

sumB=$((columnB+sumB))

我遇到这个错误的时候,我没有得到我想要的结果: ") 语法错误:无效的算术运算符(错误标记为“

这是一般代码:

sumA=0
sumB=0

while IFS= read -r line
do

columnA="$(cut -d':' -f1 <<<$line)"
sumA=$((columnA+sumA))

columnB="$(cut -d':' -f2 <<<$line)"
sumB=$((columnB+sumB))

done < "random.txt"

echo $sumA
echo $sumB

有什么想法吗?

不要使用“cut”,而是使用内置 bash 引用:“${variable}”

ColumnA=0
ColumnB=0
while read l
do
ColumnA=$((${l//:*}+$ColumnA))
ColumnB=$((${l//*:}+$ColumnB))
done < random.txt
echo $ColumnA $ColumnB

可以简化为

awk -F: '{sumA+=; sumB+=} END {printf "%s\n%s\n", sumA, sumB}' random.txt

来自手册:

$ man awk

...
-F fs
--field-separator fs
    Use fs for the input field separator (the value of the FS predefined variable).
...