Search code examples
arraysbashshellstring-length

Longest pair of string elements or longest side of the pairs in Bash array


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:

  • Get the length of the longest pair. In the example above it would be "a bc" "d", so length 5.
  • Get the length of the longest of the fist items in the pairs. Above would be "a bc", so length 4.
  • Get the length of the longest of the second items in the pairs. Above would be "cd", so length 2.

Solution

  • 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"