-3

For instance, if I have the variable

var="dog cat owl fish"

and I want to input "cat" (the second word in a string of words separated by spaces) and get "2" returned , how would I do this in a shell script without bash?

codeforester
  • 39,467
  • 16
  • 112
  • 140

5 Answers5

3

What do you mean by "without bash"?

The following works in bash, dash, and ksh:

#!/bin/____  <- insert your shell here

input=$1
var="dog cat owl fish"

i=1
set -f
for word in $var ; do
    if [ "$word" = "$input" ] ; then
        echo $i
    fi
    i=$((i+1))
done

set -f prevents * in $var from pathname expansion. In zsh, you need set -o SH_WORD_SPLIT 1 to split $var in the for loop.

choroba
  • 231,213
  • 25
  • 204
  • 289
1

With some core utilities:

echo "$var" | tr " " "\n" | grep -n "$input" | cut -d: -f1
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

This information came from a previous post. I just altered it to hopefully fit your problem.

var="dog cat owl fish"
target=$1
tokens=$(echo $var | sed 's/[.\\\/;,?!:]//g') # Add any missing punctuation marks here
pos=0
for token in $tokens
do
    pos=$(($pos + 1))
    if [[ "$token" = "$target" ]] #you could use just $1 if you wanted to instead declaring the target variable.
    then
        echo $pos
    fi
done
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
B. Cratty
  • 1,725
  • 1
  • 17
  • 32
0

Since you mentioned awk in the comments:

$ echo $var | awk -v s=cat '{for(i=1;i<=NF;i++)if($i=="cat")print i}'
2

Explained:

echo $var |            # echo $var to awk
awk -v s=cat '{        # parameterized search word
    for(i=1;i<=NF;i++) # iterate every word
        if($i==s)      # if current word is the searched one
            print i    # print its position
}'

If it's possible to have newlines in the var (sh mentioned):

$ var="dog cat\nowl fish"                
$ echo $var
dog cat
owl fish
$ echo $var | awk -v RS="^$" -v s=owl '{for(i=1;i<=NF;i++)if($i==s)print i}'
3
James Brown
  • 36,089
  • 7
  • 43
  • 59
0
animals="dog cat owl fish"
tokens=( $animals )
echo ${tokens[1]}