查找元素

数组和集合 / 数组

numbers=(2 3 5 7 11 13 17)

#bash has no "in" for arrays: the elements are joined into one string
#with spaces around, so " 5 " cannot match a part of 15
[[ " ${numbers[*]} " == *" 5 "* ]] && contain5=true || contain5=false
#contain5 is true
[[ " ${numbers[*]} " == *" 10 "* ]] && contain10=true || contain10=false
#contain10 is false

#the index: a function prints it, -1 if there is no such value
indexOf() {
    local value=$1
    shift
    local i=0
    local item
    for item in "$@"; do
        if [[ $item == "$value" ]]; then
            echo "$i"
            return
        fi
        i=$((i + 1))
    done
    echo -1
}

index5=$(indexOf 5 "${numbers[@]}")
#index5 is 2
index10=$(indexOf 10 "${numbers[@]}")
#index10 is -1

#how many times: grep -c counts the lines, -x wants the whole line
number2=(1 9 8 3 1 6 71)
containNum=$(printf '%s\n' "${number2[@]}" | grep -cx 1)
#containNum is 2

echo "contain5 is $contain5"
echo "contain10 is $contain10"
echo "index5 is $index5"
echo "index10 is $index10"
echo "containNum is $containNum"