加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 22:06:46 所属栏目:安全 来源:网络整理
导读:只是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有关吗
只是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]}"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读