【问题标题】:How can I use grep to return the full string of text that a searched term is nested in?如何使用 grep 返回嵌套搜索词的完整文本字符串?
【发布时间】:2016-11-09 13:32:45
【问题描述】:
假设我有以下文字:
大家好,我叫拉里,这是我的个人资料 www.cool.com/imgreat,请查看。
egrep -i --color 'cool' filename
仅突出显示字符串中出现的“cool”,但我希望它返回“www.cool.com/imgreat”
【问题讨论】:
标签:
unix
command-line
grep
【解决方案1】:
您可以使用简单的awk 逐个循环访问条目,如果任何行条目与cool 匹配,则打印整个单词。
$ string="Hi my name is Larry and this is my profile www.cool.com/imgreat please check it out"
$ awk '{for(i=1;i<=NF;i++) {if ($i ~ /cool/){print $i}}}' <<<"$string"
www.cool.com/imgreat
【解决方案2】:
试试这个,这应该是匹配网站模式的正则表达式(这不包括 http/https):
[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&=]*)
所以你的命令应该是:
egrep -i --color '[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&=]*)' filename
【解决方案3】:
如果要提取WS分隔的包含cool的部分,可以使用awk
$ awk '{for(i=1;i<NF;i++) if ($i ~ /cool/)print $i}' <<< """Hi my name is Larry and this is my profile www.cool.com/imgreat please check it out."""
www.cool.com/imgreat