grep 匹配后一定数量的单词

grep 匹配后一定数量的单词

我如何 grep 关键字和接下来的四个单词。例如,假设我们有这样一段:

Meta Stack Exchange is where users like you discuss bugs, features, and 
support issues that affect the software powering all 167 Stack Exchange 
communities.

我想 grep 关键字“Exchange”和接下来的四个单词,因此输出是“Exchange 是用户喜欢的地方”

我用了 :

grep -Eo "Exchange" 

我必须添加到此命令中以控制关键字后的 grep 数量(单词、数字、图表...)

答案1

也许使用空格和非空格字符序列?

$ grep -Eo 'Exchange([[:space:]]+[^[:space:]]+){4}' << EOF
Meta Stack Exchange is where users like you discuss bugs, features, and 
support issues that affect the software powering all 167 Stack Exchange 
communities.
EOF
Exchange is where users like

或者(perl 风格,如果你的 grep 支持的话)

$ grep -Eo 'Exchange(\s+\S+){4}' << EOF
Meta Stack Exchange is where users like you discuss bugs, features, and 
support issues that affect the software powering all 167 Stack Exchange 
communities.
EOF
Exchange is where users like

注意 grep 不跨行匹配 - 对于多行匹配,您可以使用 pcregrep 反而

相关内容