【问题标题】:Grep everything after pattern whose # of lines are inconsistent对行数不一致的模式后的所有内容进行grep
【发布时间】:2021-02-21 08:57:14
【问题描述】:

我正在尝试找到一种方法来从一堆类似文件中提取特定文本。示例:

-
Blah1: stuff
Blah2: stuff
Blah3:
 - bingo
 - this
 - is
 - what im looking for
Blah4: stuff
-
Blah1: stuff
Blah2: stuff
Blah3:
 - bingo this is
 - what im looking for
Blah4: stuff

但是,“我正在寻找的宾果游戏”并不总是 4 行,有时是 2 或 15 行遵循相同的模式,但总是以新行开头并以 - 开头,而 Blah3 始终是 Blah3

我需要一种方法来获得仅显示的输出

Blah3:
- Bingo
- this
- is
- what im looking for
Blah3:
- bingo this is
- what im looking for

尝试在 grep 上使用 -A,但 Blah3: 之后出现的行数不一致,并尝试在 grep 中使用相当多的正则表达式,但仍然无法获得我正在寻找的输出

【问题讨论】:

标签: bash sed grep


【解决方案1】:

这可能对你有用(GNU sed):

sed -n '/^\S\+:/h;G;/^Blah3:/MP;d' file

使用-n 选项关闭隐式打印。

将任意键复制到保留空间。

将保持空间附加到每一行。

如果存在所需的键,则打印模式空间中的第一行。

注意正则表达式上的M 标志允许^ 匹配行首。

替代方案:

sed -n '/^Blah3:/{:a;p;n;/^ -/ba}' file

【讨论】:

    猜你喜欢
    • 2012-05-08
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 2019-06-28
    相关资源
    最近更新 更多