How to find the index of a word in a string in bash?

Solution 1:

Bash performs word splitting in strings all by itself – in fact, more often than not, avoiding that is an issue, and the reason quoting is so important. It’s easy to leverage that in your case: just put your string into an array without quoting it – bash will use word splitting to separate the individual elements. Assuming your string is stored in the variable $str,

ar=($str) # no quotes!

will return an array of 5 elements. Your array index is your word index (counting up from 0, like in most scripting and programming languages), i.e. “Age” is accessed using

${ar[1]}  # 0 => Name, 1 => Age, 2 => Sex, 3 => ID, 4 => Address

or, if you need to find the element index by content, loop over the array, i.e.

function el_index {
    cnt=0; for el in "${ar[@]}"; do
        [[ $el == "$1" ]] && echo $cnt && break
        ((++cnt))
    done
}
el_index "Age" # => 1

Solution 2:

$ export FOO="Name   Age Sex  ID         Address"

Replace *Age with Age -- this will remove anything before "Age":

$ echo ${FOO/*Age/Age}
Age Sex ID Address

Get anything before "Age"

$ echo ${FOO/Age*/}
Name

Get the length of that string (which is the index of "Age"):

$ BEGIN=${FOO/Age*/}
$ echo ${#BEGIN}
7

Solution 3:

This is a 7-years-old question, but some may need the answer in pure bash.

STRING="Name   Age Sex  ID         Address"
INDEXOF_AGE=${#${STRING/Age*/}}
echo $INDEXOF_AGE