gpt4 book ai didi

unix - 为两个字符串之间最后一次出现的字符串生成一个日志文件

转载 作者:行者123 更新时间:2023-12-03 10:48:48 27 4
gpt4 key购买 nike

我有一个日志文件 trace.log .在其中,我需要 grep 字符串中包含的内容 <tag></tag> .这对字符串有多组,我只需要返回最后一组之间的内容(换句话说,来自日志文件的tail)。

额外的信用:只有当内容包含“testString”时,我才能以任何方式返回包含在两个字符串中的内容?

谢谢你看。

编辑:搜索参数 和 包含在不同的行中,大约有 100 行内容将它们分开。内容是我所追求的......

最佳答案

使用 tac反过来打印文件,然后 grep -m1只打印一个结果。后视和前视检查 <tag> 之间的文本和 </tag> .

tac a | grep -m1 -oP '(?<=tag>).*(?=</tag>)'

测试

鉴于此文件
$ cat a
<tag> and </tag>
aaa <tag> and <b> other things </tag>
adsaad <tag>and last one</tag>

$ tac a | grep -m1 -oP '(?<=tag>).*(?=</tag>)'
and last one

更新

EDIT: The search parameters and are contained on different lines with about 100 lines of content separating them. The content is what I'm after...



然后就有点棘手了:
tac file | awk '/<\/tag>/ {p=1; split($0, a, "</tag>"); $0=a[1]};
/<tag>/ {p=0; split($0, a, "<tag>"); $0=a[2]; print; exit};
p' | tac

这个想法是反转文件并使用标志 p检查是否 <tag>已经出现与否。 </tag>时开始打印 <tag>时出现并完成来了(因为我们正在以相反的方式阅读)。
  • split($0, a, "</tag>"); $0=a[1];获取之前的数据</tag>
  • split($0, a, "<tag>" ); $0=a[2];获取<tag>之后的数据

  • 测试

    给定一个文件 a像这样:
    <tag> and </tag>
    aaa <tag> and <b> other thing
    come here
    and here </tag>

    some text<tag>tag is starting here
    blabla
    and ends here</tag>

    输出将是:
    $ tac a | awk '/<\/tag>/ {p=1; split($0, a, "</tag>"); $0=a[1]}; /<tag>/ {p=0; split($0, a, "<tag>"); $0=a[2]; print; exit}; p' | tac
    tag is starting here
    blabla
    and ends here

    关于unix - 为两个字符串之间最后一次出现的字符串生成一个日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19681642/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com