bash 在bash中搜索数组返回索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9010578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:25:25  来源:igfitidea点击:

Search array return index in bash

arraysbashsyntax

提问by matt

Just pesuocode but this is essentially what I would like to do.

只是 pesuocode 但这基本上是我想做的。

Array=("1" "Linux" "Test system"
       "2" "Windows" "Workstation"
       "3" "Windows" "Workstation")


echo "number " ${array[search ""]} "is a" ${array[search "" +1]} ${array[search "" +2])}

Is this possible with bash? I could only find info on search and replace. I didn't see anything That would return and index.

这可以用 bash 吗?我只能找到有关搜索和替换的信息。我没有看到任何会返回和索引的东西。

回答by user123444555621

Something like that should work:

这样的事情应该工作:

search() {
    local i=1;
    for str in "${array[@]}"; do
        if [ "$str" = "" ]; then
            echo $i
            return
        else
            ((i++))
        fi
    done
    echo "-1"
}

While looping over the array to find the index is certainly possible, this alternative solution with an associative array is more practical:

虽然循环遍历数组以找到索引肯定是可能的,但这种带有关联数组的替代解决方案更实用:

array=([1,os]="Linux"   [1,type]="Test System"
       [2,os]="Windows" [2,type]="Work Station"
       [3,os]="Windows" [3,type]="Work Station")

echo "number  is a ${array[,os]} ${array[,type]}"

回答by Carl Norum

You could modify this example from this linkto return an index without much trouble:

您可以从此链接修改此示例以轻松返回索引:

# Check if a value exists in an array
# @param  mixed  Needle  
# @param  array  Haystack
# @return  Success (0) if value exists, Failure (1) otherwise
# Usage: in_array "$needle" "${haystack[@]}"
# See: http://fvue.nl/wiki/Bash:_Check_if_array_element_exists
in_array() {
    local hay needle=
    shift
    for hay; do
        [[ $hay == $needle ]] && return 0
    done
    return 1
}