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

只谈情不闲聊 提交于 2019-12-13 08:39:58

问题


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


来源:https://stackoverflow.com/questions/45011858/unix-how-to-find-what-place-a-word-comes-in-a-sentence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!