Arithmetic operation on all elements in BASH array -
say have bash array integers:
declare -a arr=( 1 2 3 )
and want arithmetic operation on each element, e.g. add 1. there altenative loop:
for (( i=0 ; i<=${#arr[@]}-1 ; i++ )) ; arr[$i]=$(( ${arr[$i]} + 1 )) done
i have tried few options:
arr=$(( ${arr[@]} + 1 ))
fails, while
arr=$(( $arr + 1 ))
results in
echo ${arr[@]} 2 2 3
thus first (zeroth) element being changed.
i read awk
solutions, know if bash arithmetics support such batch operations on each array element.
i know question not fresh new can accomplish want declaring array integer
, applying substitution:
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 well:
value=3 declare -ia 'arr_multd=( "${arr[@]/%/*$value}" )' echo "arr_multd: ${arr_multd[*]}"
outputs:
arr_multd: 3 6 9
Comments
Post a Comment