Unix - How to find what place a word comes in a se

2019-09-19 17:52发布

问题:

Basically, I'm writing a shell script in Unix and I need to retrieve a value that says what place a word occurs in a sentence/string and then store that value in a variable.

For example, the word "blue" is the third word in the following sentence "the fast blue car". Therefore, I'd like the value for this word to be 3 and store it in a variable called $blue. I.e. echo $blue would print out the number 3.

All the examples I've found so far print out the position of a word in terms of characters not words.

回答1:

Maybe something like this?

text="The quick brown fox jumps over the lazy dog."
tokens=$(echo $text | sed 's/[.\\\/;,?!:]//g') # Add any missing punctuation marks here
$pos = 0
for token in $tokens
do
    pos=$(($pos + 1))
    if [[ "$token" == "fox" ]]
    then
        echo $pos
    fi
done

This'll print the position of the word "fox" (4 in this case) out to the command line. Multiple occurrences of the word will yield multiple outputs.



回答2:

Here's another in awk. Borrowing @SebastianLenartowicz's $text:

$ text="the quick brown fox jumps over the lazy dog"  # in lower and no punctuations

$ echo $text | awk -v RS="[ \n]" -v s=fox '$0==s{print NR}'
4

Explained:

  • -v RS="[ \n]" Record Separator to space or newline
  • -v s=foxsearch word goes to script in variable s
  • $0==s{print NR} if the record ($0) equals s print the row or record number NR


标签: bash shell unix sh