Say we have a BASH array with integers:
declare -a arr=( 1 2 3 )
and I want to do an arithmetic operation on each element, e.g. add 1. Is there an altenative to a for loop:
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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With