[英]Arithmetic operation on all elements in BASH array
Say we have a BASH array with integers: 假设我们有一个带有整数的BASH数组:
declare -a arr=( 1 2 3 )
and I want to do an arithmetic operation on each element, eg add 1. Is there an altenative to a for loop: 并且我想对每个元素进行算术运算,例如加1。for循环是否有替代方法:
for (( i=0 ; i<=${#arr[@]}-1 ; i++ )) ; do
arr[$i]=$(( ${arr[$i]} + 1 ))
done
I have tried a few options: 我尝试了几种选择:
arr=$(( ${arr[@]} + 1 ))
fails, while 失败,而
arr=$(( $arr + 1 ))
results in 结果是
echo ${arr[@]}
2 2 3
thus only the first (zeroth) element being changed. 因此,仅第一个(零个)元素被更改。
I read about awk
solutions, but would like to know if BASH arithmetics support such batch operations on each array element. 我阅读了有关
awk
解决方案的信息,但想知道BASH算术是否支持每个数组元素上的此类批处理操作。
I know your question is not fresh new but you can accomplish what you want by declaring your array as integer
and then applying a substitution: 我知道您的问题不是新鲜事物,但是您可以通过将数组声明为
integer
然后应用替换来完成所需的工作:
declare -ia arr=( 1 2 3 )
value=1
declare -ia 'arr_added=( "${arr[@]/%/+$value}" )'
echo "arr_added: ${arr_added[*]}"
value=42
declare -ia 'arr_added=( "${arr[@]/%/+$value}" )'
echo "arr_added: ${arr_added[*]}"
It outputs: 它输出:
arr_added: 2 3 4
arr_added: 43 44 45
You can perform other math operations as well: 您还可以执行其他数学运算:
value=3
declare -ia 'arr_multd=( "${arr[@]/%/*$value}" )'
echo "arr_multd: ${arr_multd[*]}"
Outputs: 输出:
arr_multd: 3 6 9
you can use eval to have the feeling of lambda function (not sure about the syntax but this should be the main idea ) : 您可以使用eval来感受lambda函数(不确定语法,但这应该是主要思想):
eval "function add1 { x=$1; y=$((x+1)) ; return $y; }"
for (( i=0 ; i<=${#arr[@]}-1 ; i++ )) ; do
add1 ${arr[i]}
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.