Unix - 如何找到一个词在句子中出现的位置 [英] Unix - How to find what place a word comes in a sentence

查看:51
本文介绍了Unix - 如何找到一个词在句子中出现的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我正在 Unix 中编写一个 shell 脚本,我需要检索一个值,该值说明某个词出现在句子/字符串中的哪个位置,然后将该值存储在一个变量中.

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.

例如,单词blue"是以下句子the fast blue car"中的第三个单词.因此,我希望这个词的值为 3 并将其存储在一个名为 $blue 的变量中.IE.echo $blue 会打印出数字 3.

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.

推荐答案

也许是这样?

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

这会将单词fox"(在本例中为 4)的位置打印到命令行.该词多次出现将产生多个输出.

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.

这篇关于Unix - 如何找到一个词在句子中出现的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆