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

String 如何在bash中添加带有整数的字符串?,string,bash,shell,unix,integer,String,Bash,Shell,Unix,Integer,我想读取一个随机txt,其中包含以下形式的随机整数: 2:10 4:4 10:15 22:5 然后我想求每列的和。首先,我想拆分每一行,就像每一行都是字符串一样: columnA="$(cut -d':' -f1 <<<$line)" columnB="$(cut -d':' -f2 <<<$line)" 我得到了我想要的结果,但也有这个消息 语法错误:应为操作数(错误标记为“ 第二列相同: sumB=$((c

我想读取一个随机txt,其中包含以下形式的随机整数:

2:10

4:4

10:15

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

columnA="$(cut -d':' -f1 <<<$line)"
columnB="$(cut -d':' -f2 <<<$line)"
我得到了我想要的结果,但也有这个消息

语法错误:应为操作数(错误标记为“

第二列相同:

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
sumA=0
sumB=0
而IFS=读取-r行
做
columnA=“$(cut-d':”-f1不使用“cut”,而是使用内置bash引用:“${variable}”

ColumnA=0
列B=0
当我读
做
ColumnA=$(${l/:*}+$ColumnA))
ColumnB=$(${l//*:}+$ColumnB))
done
它可以简化为

awk -F: '{sumA+=$1; sumB+=$2} 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). ... $man awk ... -F fs --字段分隔符fs 使用fs作为输入字段分隔符(fs预定义变量的值)。 ...
用于检查您的语法。您的代码应该适用于所描述的输入文件
random.txt
。您的实际输入文件是否包含十进制数?可能是因为您的文件中有空行?与minePerfect相同的错误非常感谢!您能解释一下awk-F的作用吗?以及您为什么选择使用它@ς
man awk
:“
-F fs-字段分隔符fs使用fs作为输入字段分隔符(fs预定义变量的值)。
“@code>等于
var a++var b
,甚至更短。
awk -F: '{sumA+=$1; sumB+=$2} 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). ...