Get the index of a value in a Bash array

后端 未结 15 511
说谎
说谎 2021-01-30 03:41

I have something in bash like

myArray=(\'red\' \'orange\' \'green\')

And I would like to do something like

echo ${         


        
相关标签:
15条回答
  • 2021-01-30 04:38

    A little more concise and works in Bash 3.x:

    my_array=(red orange green)
    value='green'
    
    for i in "${!my_array[@]}"; do
       [[ "${my_array[$i]}" = "${value}" ]] && break
    done
    
    echo $i
    
    0 讨论(0)
  • 2021-01-30 04:38

    I like that solution:

    let "n=(`echo ${myArray[@]} | tr -s " " "\n" | grep -n "green" | cut -d":" -f 1`)-1"
    

    The variable n will contain the result!

    0 讨论(0)
  • 2021-01-30 04:41

    This outputs the 0-based array index of the query (here "orange").

    echo $(( $(printf "%s\n" "${myArray[@]}" | sed -n '/^orange$/{=;q}') - 1 ))
    

    If the query does not occur in the array then the above outputs -1.

    If the query occurs multiple times in the array then the above outputs the index of the query's first occurrence.

    Since this solution invokes sed, I doubt that it can compete with some of the pure bash solutions in this thread in efficiency.

    0 讨论(0)
提交回复
热议问题