保留第一行并删除所有段落的所有内容(直至某个模式)

保留第一行并删除所有段落的所有内容(直至某个模式)

我有一个包含这样的数据的日志文件。

criteria (NO-NO) data/speed/profile_1
    someting something useless data
    something something useless data
    more useless data
        Old run: exit speed=22.5
        Old run: ramp speed=15.2
        New run: exit speed=28.2
        New run: ramp speed=19.3

criteria (NO-NO) data/speed/profile 3
    someting something useless data
    something something useless data
    more useless data
        Old run: exit speed=25.3
        Old run: ramp speed=18.6
        New run: exit speed=29.5
        New run: ramp speed=17.9

这是我想要的输出:

criteria (NO-NO) data/speed/profile_1
        Old run: exit speed=22.5
        Old run: ramp speed=15.2
        New run: exit speed=28.2
        New run: ramp speed=19.3

criteria (NO-NO) data/speed/profile 3
        Old run: exit speed=25.3
        Old run: ramp speed=18.6
        New run: exit speed=29.5
        New run: ramp speed=17.9

我曾经awk 'NR==1||c-->0;/^$/{c=1}' logs.txt获取每个段落的第一行,并且曾经sed 's/^.*\(Ref\)/\1/' logs.txt删除“Ref”一词之前的所有内容,但所做的只是删除制表符。我不确定如何组合所有内容以获得我想要的输出。

答案1

你可以做一些有状态的事情,比如

/first-pattern/ {print; p = 0} /second-pattern/ {p = 1} p

前任。

$ awk '/^criteria/ {print; p = 0} /(Old|New) run:/ {p = 1} p' file.log
criteria (NO-NO) data/speed/profile_1
        Old run: exit speed=22.5
        Old run: ramp speed=15.2
        New run: exit speed=28.2
        New run: ramp speed=19.3

criteria (NO-NO) data/speed/profile 3
        Old run: exit speed=25.3
        Old run: ramp speed=18.6
        New run: exit speed=29.5
        New run: ramp speed=17.9

答案2

鉴于您发布的示例输入/输出,您所需要的只是:

$ grep -v '^    [^ ]' file
criteria (NO-NO) data/speed/profile_1
        Old run: exit speed=22.5
        Old run: ramp speed=15.2
        New run: exit speed=28.2
        New run: ramp speed=19.3

criteria (NO-NO) data/speed/profile 3
        Old run: exit speed=25.3
        Old run: ramp speed=18.6
        New run: exit speed=29.5
        New run: ramp speed=17.9

如果这不是您所需要的全部,那么编辑您的问题以提供更真正具有代表性的示例输入/输出。

答案3

带有范围运算符的 Gnu sed 适合这种情况:

$ sed -Ee '
    /^criteria/,/^$/!d
    //b
    /(Old|New) run:/!d
' file

答案4

尝试使用以下命令

awk '/criteria/||/:/{print $0}' filename

相关内容