Get the index of a value in a Bash array

后端 未结 15 527
说谎
说谎 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:18

    This might just work for arrays,

    my_array=(red orange green)
    echo "$(printf "%s\n" "${my_array[@]}")" | grep -n '^orange$' | sed 's/:orange//'
    

    Output:

    2
    

    If you want to find header index in a tsv file,

    head -n 1 tsv_filename | sed 's/\t/\n/g' | grep -n '^header_name$' | sed 's/:header_name//g'
    

提交回复
热议问题