[英]grep regular expression returns full line
Im trying to print everything after a keyword using grep but the command returns the whole line. 我试图使用grep打印关键字后的所有内容,但命令返回整行。 Im using the following:
我使用以下内容:
grep -P (\skeyword\s)(.*)
an example line is: 示例行是:
abcdefg keyword hello, how are you.
The result should be hello, how are you
but instead it gives the full line. 结果应该是
hello, how are you
但它给出了整行。 Am I doing something wrong here? 我在这里做错了吗?
You need to use -o
( only matching ) parameter and \\K
( discards the previously matched characters ) or a positive lookbehind. 您需要使用
-o
( 仅匹配 )参数和\\K
( 丢弃先前匹配的字符 )或正向lookbehind。
grep -oP '\skeyword\s+\K.*' file
\\K
keeps the text matched so far out of the overall regex match. \\K
保持文本匹配到目前为止整个正则表达式匹配。 \\s+
matches one or more space characters. \\s+
匹配一个或多个空格字符。
Example: 例:
$ echo 'abcdefg keyword hello, how are you.' | grep -oP '\skeyword\s+\K.*'
hello, how are you.
By default, Grep prints lines that match. 默认情况下,Grep打印匹配的行。 To print only matching expressions try the '-o' option.
要仅打印匹配的表达式,请尝试使用'-o'选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.