簡體   English   中英

在bash中搜索數組返回索引

[英]Search array return index in bash

只是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有關嗎? 我只能找到有關搜索和替換的信息。 我沒有看到任何可以返回和索引的東西。

這樣的東西應該工作:

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]}"

您可以從此鏈接修改此示例以返回索引而不會有太多麻煩:

# 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM