【问题标题】:Return only the regex match, not the whole line只返回正则表达式匹配,而不是整行
【发布时间】:2013-08-30 18:39:01
【问题描述】:

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

This is key word1 line 1.

This is line 2.

This is key word2 line 3. 

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

This is key word1 line 1.

This is key word2 line 2. 

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

key word1

key word2

有没有办法做到这一点?

【问题讨论】:

标签: regex sed grep


【解决方案1】:

grep(1) 有一个 -o 标志,它只输出行的匹配部分。来自man page

  -o, --only-matching
      Show only the part of a matching line that matches PATTERN.

但是,您的模式不适合获得您想要的输出。试试:

$ egrep -o 'key \w+' file 
key word1
key word2

【讨论】:

    猜你喜欢
    • 2023-01-25
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 2022-01-14
    • 1970-01-01
    • 2023-01-07
    相关资源
    最近更新 更多