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

后端 未结 9 2301
眼角桃花
眼角桃花 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:32
    #!/bin/bash
    
    test="name"
    
    array=('hello' 'world' 'my' 'yourname' 'name' 'is' 'perseus')
    nelem=${#array[@]}
    [[ "${array[0]} " =~ "$test " ]] || 
    [[ "${array[@]:1:$((nelem-1))}" =~ " $test " ]] || 
    [[ " ${array[$((nelem-1))]}" =~ " $test" ]] && 
    echo "found $test" || echo "$test not found"
    

    Just treat the expanded array as a string and check for a substring, but to isolate the first and last element to ensure they are not matched as part of a lesser-included substring, they must be tested separately.

    0 讨论(0)
  • 2021-02-13 19:35

    With bash 4, the closest thing you can do is use associative arrays.

    declare -A map
    for name in hello world my name is perseus; do
      map["$name"]=1
    done
    

    ...which does the exact same thing as:

    declare -A map=( [hello]=1 [my]=1 [name]=1 [is]=1 [perseus]=1 )
    

    ...followed by:

    tgt=henry
    if [[ ${map["$tgt"]} ]] ; then
      : found
    fi
    
    0 讨论(0)
  • 2021-02-13 19:35
    array=('hello' 'world' 'my' 'name' 'is' 'perseus')
    regex="^($(IFS=\|; echo "${array[*]}"))$"
    
    test='henry'
    [[ $test =~ $regex ]] && echo "found" || echo "not found"
    
    0 讨论(0)
提交回复
热议问题