bash Bash正则表达式在句子中查找特定单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11419885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:43:26  来源:igfitidea点击:

Bash regex finding particular words in a sentence

regexstringbashscripting

提问by JDS

I have a sentence like this:

我有这样一句话:

"The dog jumped over the moon because he likes jumping"

And I want to find all words that match jump.*, i.e. jumpedand jumping. How can I do this?

我想找到所有匹配的单词jump.*,即jumpedjumping。我怎样才能做到这一点?

Currently I have the sentence in a variable, $sentence. And I know the match word that I want to test against, e.g. $testis jump.

目前我有一个变量中的句子,$sentence. 而且我知道我要测试的匹配词,例如$testjump.

Thank you

谢谢

采纳答案by morja

Try this regex:

试试这个正则表达式:

/\bjump.*?\b/

See here. \bmatches word boundaries and jump.*?everything between that starts with jump.

这里\b匹配单词边界以及jump.*?jump.开头的所有内容。

In bash you can use it with grep:

在 bash 中,您可以将它与 grep 一起使用:

echo $sentence | grep -oP "\b$test.*?\b"

回答by Todd A. Jacobs

A Pipe-Free Bash Solution

无管道 Bash 解决方案

If you want to do this purely in Bash, you can use the regular expression matching operator and the built-in BASH_REMATCHvariable to hold the results. For example:

如果你想纯粹在 Bash 中做到这一点,你可以使用正则表达式匹配运算符和内置的BASH_REMATCH变量来保存结果。例如:

re='\bjump[[:alpha:]]*\b'
string="The dog jumped over the moon because he likes jumping"
for word in $string; do
    [[ "$word" =~ $re ]] && echo "${BASH_REMATCH}"
done

Given your corpus, this correctly returns the following results:

鉴于您的语料库,这将正确返回以下结果:

jumped
jumping

回答by William Pursell

echo $sentence | tr ' ' '\n' | grep "^$test"

To be more thorough:

更彻底:

echo $sentence | tr '[[:space:]]' '\n' | grep "^$test"

回答by Clay

http://www.linuxjournal.com/content/bash-regular-expressions

http://www.linuxjournal.com/content/bash-regular-expressions

looks like it might help you. (I'm no good at regex or bash, sorry)

看起来它可能对你有帮助。(我不擅长正则表达式或 bash,抱歉)