How can I check if a string is in an array without iterating over the elements?

后端 未结 9 2298
眼角桃花
眼角桃花 2021-02-13 18:54

Is there a way of checking if a string exists in an array of strings - without iterating through the array?

For example, given the script below, how I can correctly impl

9条回答
  •  青春惊慌失措
    2021-02-13 19:12

    Instead of iterating over the array elements it is possible to use parameter expansion to delete the specified string as an array item (for further information and examples see Messing with arrays in bash and Modify every element of a Bash array without looping).

    (
    set -f
    export IFS=""
    
    test='henry'
    test='perseus'
    
    array1=('hello' 'world' 'my' 'name' 'is' 'perseus')
    #array1=('hello' 'world' 'my' 'name' 'is' 'perseusXXX' 'XXXperseus')
    
    # removes empty string as array item due to IFS=""
    array2=( ${array1[@]/#${test}/} )
    
    n1=${#array1[@]}
    n2=${#array2[@]}
    
    echo "number of array1 items: ${n1}"
    echo "number of array2 items: ${n2}"
    echo "indices of array1: ${!array1[*]}"
    echo "indices of array2: ${!array2[*]}"
    
    echo 'array2:'
    for ((i=0; i < ${#array2[@]}; i++)); do 
       echo "${i}: '${array2[${i}]}'"
    done
    
    if [[ $n1 -ne $n2 ]]; then
       echo "${test} is in array at least once! "
    else
       echo "${test} is NOT in array! "
    fi
    )
    

提交回复
热议问题