0

I want to find the index of a word in a sentence (in my case it is a list of args)

...
elif [[ "$#" -gt "0" ]]
then
    ALL_ARGS="$@"
    echo ${ALL_ARGS} | grep -b -o target | sed 's/:.*$//'
    # 14
    TARGET_INDEX=`${ALL_ARGS} | grep -b -o target | sed 's/:.*$//'`
    # error
    # forganize.sh: line 45: .: -n: invalid option
    # .: usage: . filename [arguments]

    echo $TARGET_INDEX
...

It works in echo but I can't assign it to a variable.

Also if there is any other way to find index please let me know.

Murtrag
  • 31
  • 4

1 Answers1

0

You missed echo in your line.

TARGET_INDEX=$(echo ${ALL_ARGS} | grep -b -o target | sed 's/:.*$//')

Also if there is any other way to find index please let me know.

Do not use upper case variables. Prefer lower case variables in your scripts.

Check your script with http://shellcheck.net

Quote variable expansions. Never $var always "$var". bashfaq quotes.

var="$@" is equal to var="$*" - the result of $@ is joined using the first character in IFS. No idea if that is the intention - find the byte offset in arguments joined by spaces.

In bash you may <<<"$var" instead of echo "$var" | to save one process. Also, use printf instead of echo. See why is printf better then echo.

Do not use ` backticks. Use $(...) instead. See bash hackers obsolete.

I think cut would be simpler then sed here, I would:

target_index=$(<<<"$*" grep -bo target | cut -d: -f1)
KamilCuk
  • 120,984
  • 8
  • 59
  • 111