在 bash 中搜索数组返回索引

发布于 2024-12-28 18:21:20 字数 315 浏览 0 评论 0原文

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

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


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

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

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

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


echo "number " ${array[search "$1"]} "is a" ${array[search "$1" +1]} ${array[search "$1" +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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独孤求败 2025-01-04 18:21:21

类似的事情应该可行:

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

虽然循环数组来查找索引当然是可能的,但这种使用关联数组的替代解决方案更实用:

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

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

Something like that should work:

search() {
    local i=1;
    for str in "${array[@]}"; do
        if [ "$str" = "$1" ]; 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 $1 is a ${array[$1,os]} ${array[$1,type]}"
最丧也最甜 2025-01-04 18:21:21

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

# Check if a value exists in an array
# @param $1 mixed  Needle  
# @param $2 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=$1
    shift
    for hay; do
        [[ $hay == $needle ]] && return 0
    done
    return 1
}

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

# Check if a value exists in an array
# @param $1 mixed  Needle  
# @param $2 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=$1
    shift
    for hay; do
        [[ $hay == $needle ]] && return 0
    done
    return 1
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文