只返回正则表达式匹配,而不是整行 [英] Return only the regex match, not the whole line

查看:25
本文介绍了只返回正则表达式匹配,而不是整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多行文档,我希望从中提取特定的关键字和之后的单词.它看起来像这样:

这是关键词 1 第 1 行.这是第 2 行.这是关键字 word2 第 3 行.

如果我使用 egrep 'key [^s]+ ',输出是:

这是关键词 1 第 1 行.这是关键字 word2 第 2 行.

但是,我希望输出只是匹配而不是整行,即:

key word1关键词2

有没有办法做到这一点?

解决方案

grep(1) 有一个 -o 标志,它只输出该行的匹配部分.来自 手册页:

<块引用>

 -o, --only-matching仅显示匹配 PATTERN 的匹配行部分.

不过,您的模式无法获得您想要的输出.试试:

$ egrep -o 'key w+' 文件关键词1关键词2

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. 

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

Is there a way to do that?

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆