【问题标题】:Pull lines from log file between two strings with a third string inbetween从日志文件中提取两个字符串之间的行,中间有第三个字符串
【发布时间】:2019-03-22 22:38:30
【问题描述】:

我正在寻找一种命令行方式(在 SunOS 上)从日志文件中提取包含特定字符串的 xml 消息。

例如,日志文件可能包含以下形式的 xml 消息:

<message>
    <body>
        <tags> uniqueId="123456" </tags>
    </body>
</message>

与其他带时间戳的日志行一起。可能有多个包含相同 ID 的 xml 消息,因为同一记录可能已运行多次。

要提取当前的 xml,我有这个 awk 命令:

nawk '$0~s{for(c=NR-b;c<=NR+a;c++)r[c]=1}{q[NR]=$0}END{for(c=1;c<=NR;c++)if(r[c])print q[c]}' b=4 a=15 s="someUniqueId" file

我遇到的问题是这会拉出特定数量的行。但是,xmls 的长度可能会有所不同,我正在努力寻找一种方法来修改它,以便它找到唯一的 ID 并将所有行拉到"&lt;message&gt;",并将所有行拉到"&lt;/message&gt;"

【问题讨论】:

  • nawk 旧且缺乏功能。 /usr/xpg4/bin/awk 在功能上更接近 POSIX,因此在 Solaris 上使用 awk 是更好的选择。

标签: awk nawk


【解决方案1】:

这可能适用于完美世界(如果我理解你的问题的话):

$ cat file
<message>
    <body>
        <tags> uniqueId="123455" </tags>
    </body>
</message>
<message>
    <body>
        <tags> uniqueId="123456" </tags>      # the one we want
    </body>
</message>
<message>
    <body>
        <tags> uniqueId="123457" </tags>
    </body>
</message>

awk:

$ awk '
{ 
    b=b ORS $0                            # buffer records
}
/<message>/ {                             
    b=$0                                  # reset buffer
} 
/<\/message>/ && b~/uniqueId="123456"/ {  # if condition met at the end marker
    print b                               # output buffer
}' file

输出:

<message>
    <body>
        <tags> uniqueId="123456" </tags>      # the one we wanted
    </body>
</message>

【讨论】:

    【解决方案2】:

    你也可以试试 Perl,

    perl -0777 -ne ' while( m{(<message>(.+?)</message>)}sg ) 
         { $x=$1; if($x=~/uniqueId="123456"/) { print "$1\n" }} ' edman.txt
    

    使用来自@James 的输入,

    $ cat edman.txt
    <message>
        <body>
            <tags> uniqueId="123455" </tags>
        </body>
    </message>
    <message>
        <body>
            <tags> uniqueId="123456" </tags>      # the one we want
        </body>
    </message>
    <message>
        <body>
            <tags> uniqueId="123457" </tags>
        </body>
    </message>
    
    $ perl -0777 -ne ' while( m{(<message>(.+?)</message>)}sg ) 
        { $x=$1; if($x=~/uniqueId="123456"/) { print "$x\n" }} ' edman.txt
    <message>
        <body>
            <tags> uniqueId="123456" </tags>      # the one we want
        </body>
    </message>
    $
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      相关资源
      最近更新 更多