仅返回正则表达式匹配项,而不返回整行 [英] Return only the regex match, not the whole line
本文介绍了仅返回正则表达式匹配项,而不返回整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个多行文档,我希望从中提取特定的关键字,然后提取其中的单词.看起来像这样:
I have a multiline document from which I'm looking to extract a particular keyword and the word after that. It looks like this:
This is key word1 line 1.
This is line 2.
This is key word2 line 3.
如果我使用egrep 'key [^s]+ '
,则输出为:
If I use egrep 'key [^s]+ '
, the output is:
This is key word1 line 1.
This is key word2 line 2.
但是,我希望输出仅是匹配项,而不是整行,即:
However, I'd like the output to be the match only as opposed to the whole line, that is:
key word1
key word2
有办法吗?
推荐答案
-o
标志,该标志仅输出该行的匹配部分.从手册页:
grep(1)
has a -o
flag that outputs only the matching part of the line. From the man page:
-o, --only-matching
Show only the part of a matching line that matches PATTERN.
不过,您的模式不适合获得所需的输出.试试:
Your pattern isn't right to get the output you want, though. Try:
$ egrep -o 'key \w+' file
key word1
key word2
这篇关于仅返回正则表达式匹配项,而不返回整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文