Given an array in Bash:
my_array=("a" "b" "a bc" "d" "ab" "cd")
Considering each two consecutive items in the array as a pair
, how can I:
"a bc" "d"
, so length 5
."a bc"
, so length 4
."cd"
, so length 2
.The trick is to use a for
loop that increments an index variable by 2 every time. Everything else is basic parameter expansion to get the lengths of elements and tests against the current maximums.
#!/usr/bin/env bash
declare -a my_array=("a" "b" "a bc" "d" "ab" "cd")
declare -i maxlen_combo=0 maxlen_first=0 maxlen_second=0
IFS=""
for (( i = 0; i < ${#my_array[@]}; i += 2 )); do
if [[ $maxlen_first -lt ${#my_array[i]} ]]; then
maxlen_first=${#my_array[i]}
fi
if [[ $maxlen_second -lt ${#my_array[i+1]} ]]; then
maxlen_second=${#my_array[i+1]}
fi
combo="${my_array[*]:i:2}"
if [[ $maxlen_combo -lt ${#combo} ]]; then
maxlen_combo=${#combo}
fi
done
echo "Maximum pair length: $maxlen_combo"
echo "Maximum first length: $maxlen_first"
echo "Maximum second length: $maxlen_second"