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?
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?
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.
With some core utilities:
echo "$var" | tr " " "\n" | grep -n "$input" | cut -d: -f1
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
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
animals="dog cat owl fish"
tokens=( $animals )
echo ${tokens[1]}