将字符串 "a+b+c" 计算为 shell 脚本中的实际数字总和
Evaluate string "a+b+c" as an actual sum of numbers in shell scripting
我正在尝试制作一个脚本来读取逗号分隔值的文件,如下所示:
10,20,30,40
30,50,20,80
我希望它获取每一行并打印将其中所有数字相加的结果,有点像应用地图功能,可能有很多更好的方法可以做到这一点,但我现在很好奇如果可能的话:
#!/bin/bash
while IFS='' read -r line; do
field=$line
result=$(echo $line | tr ',' '+')
echo $(expr $result) #Here i would have the string "10+20+30+40"
done < <(cat "")
我想要的是得到添加这些而不是字符串的结果,我不知道这是否可能。
抱歉解释混乱。
您需要在 +
和数字之间添加一个 space。相反:
#!/bin/bash
while IFS='' read -r line; do
field=$line
result=$(echo $line | sed 's/,/ + /g')
echo $(expr $result)
done < ""
您也不需要 cat
,您可以直接将其重定向到循环中。
您可以使用 bc
:
#!/bin/bash
while IFS='' read -r line; do
echo $line | tr ',' '+' | bc
done < ""
使用算术展开式 $((...))
而不是 expr
:
while read -r line ; do
result=${line//,/+}
echo $(($result))
done < ""
我还使用了参数扩展而不是 tr
。
您可以通过 awk
一行实现这一点:
awk -F, '[=10=] {s=0;for(i=1;i<=NF;i++) s+=$i; print s}' ""
输出:
100
180
解释:
-F,
: 设置 ,
作为字段分隔符
[=15=] {..}
: 确保行 ([=16=]
) 不为空
- 最后,总结每一行的所有字段(
s+=$i
)
您可以将这些值拆分成一个数组,然后使用一个简单的循环遍历该数组并添加这些值。
#!/bin/bash
while IFS='' read -r line; do
IFS=, read -a values <<< "$line"
result=0
for i in ${values[@]}; do
result=$((result + i))
done
echo "$result"
done < ""
一种更短但更神秘的方法是使用 bash
参数扩展将每个逗号转换为 space 包围的加号,然后传递结果 unquoted 扩展为 expr
.
while IFS='' read -r line; do
expr ${line//,/ + }
done
我正在尝试制作一个脚本来读取逗号分隔值的文件,如下所示:
10,20,30,40
30,50,20,80
我希望它获取每一行并打印将其中所有数字相加的结果,有点像应用地图功能,可能有很多更好的方法可以做到这一点,但我现在很好奇如果可能的话:
#!/bin/bash
while IFS='' read -r line; do
field=$line
result=$(echo $line | tr ',' '+')
echo $(expr $result) #Here i would have the string "10+20+30+40"
done < <(cat "")
我想要的是得到添加这些而不是字符串的结果,我不知道这是否可能。 抱歉解释混乱。
您需要在 +
和数字之间添加一个 space。相反:
#!/bin/bash
while IFS='' read -r line; do
field=$line
result=$(echo $line | sed 's/,/ + /g')
echo $(expr $result)
done < ""
您也不需要 cat
,您可以直接将其重定向到循环中。
您可以使用 bc
:
#!/bin/bash
while IFS='' read -r line; do
echo $line | tr ',' '+' | bc
done < ""
使用算术展开式 $((...))
而不是 expr
:
while read -r line ; do
result=${line//,/+}
echo $(($result))
done < ""
我还使用了参数扩展而不是 tr
。
您可以通过 awk
一行实现这一点:
awk -F, '[=10=] {s=0;for(i=1;i<=NF;i++) s+=$i; print s}' ""
输出:
100
180
解释:
-F,
: 设置,
作为字段分隔符[=15=] {..}
: 确保行 ([=16=]
) 不为空- 最后,总结每一行的所有字段(
s+=$i
)
您可以将这些值拆分成一个数组,然后使用一个简单的循环遍历该数组并添加这些值。
#!/bin/bash
while IFS='' read -r line; do
IFS=, read -a values <<< "$line"
result=0
for i in ${values[@]}; do
result=$((result + i))
done
echo "$result"
done < ""
一种更短但更神秘的方法是使用 bash
参数扩展将每个逗号转换为 space 包围的加号,然后传递结果 unquoted 扩展为 expr
.
while IFS='' read -r line; do
expr ${line//,/ + }
done