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

后端 未结 9 2279
眼角桃花
眼角桃花 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:14

    There will always technically be iteration, but it can be relegated to the shell's underlying array code. Shell expansions offer an abstraction that hide the implementation details, and avoid the necessity for an explicit loop within the shell script.

    Handling word boundaries for this use case is easier with fgrep, which has a built-in facility for handling whole-word fixed strings. The regular expression match is harder to get right, but the example below works with the provided corpus.

    External Grep Process

    array=('hello' 'world' 'my' 'name' 'is' 'perseus')
    word="world"
    if echo "${array[@]}" | fgrep --word-regexp "$word"; then
        : # do something
    fi
    

    Bash Regular Expression Test

    array=('hello' 'world' 'my' 'name' 'is' 'perseus')
    word="world"
    if [[ "${array[*]}" =~ (^|[^[:alpha:]])$word([^[:alpha:]]|$) ]]; then
        : # do something
    fi
    

提交回复
热议问题