Grep 并合并文件的两个时间戳行之间的行 - Unix

Grep 并合并文件的两个时间戳行之间的行 - Unix

我正在尝试从日志文件中 grep 特定模式的行Logfile.txt并将输出重定向到新的文本文件1.txt。日志文件^M中包含一些控制字符,并且这些行将在时间戳行之间可用,因此我尝试将所有这些多行合并为单行,并尝试将其附加到预期结果中,如果前一行包含Execute模式它。但无法按预期获得

日志文件.txt

    1993-01-04 06:24:03,068 INFO  b: [Cool: read-189231]: Opening the File
    1993-01-04 06:24:13,068 INFO  b: [Cool: read-189231]: Checking the content
    1993-01-04 06:24:23,148 INFO  b: [Cool: read-189231]: Setting the session:
    1993-01-04 06:24:25,068 INFO  b: [Cool: read-189231]: Checking the content
    1993-01-04 06:24:25,068 INFO  b: [Cool: read-189231]: Compiling the query
    1993-01-04 06:24:27,148 INFO  ab: [Cool: read-189231]: Completed
    1993-01-04 06:25:22,168 INFO  ba: [Cool: read-190983]: Execute ^M
    I am just checking the answer ^M
    Need your support for the workaround ^M
    This log has some control character ^M
    1993-01-04 06:25:22,168 INFO  a: [Cool: read-190983]: Main Execution completed
    1993-01-04 06:25:52,188 INFO  ba: [Cool: read-190983]: Execute the line : How are you
    1993-01-04 06:26:45,268 INFO  a: [Cool: read-190983]: Exiting

代码 - 我的发现

egrep -wah 'Setting the session:|Checking the line|Completed|Execute|Exiting' Logfile.txt > 1.txt

预期结果

1993-01-04 06:24:23,148 INFO  b: [Cool: read-189231]: Setting the session:
1993-01-04 06:24:25,068 INFO  b: [Cool: read-189231]: Checking the line
1993-01-04 06:24:27,148 INFO  ab: [Cool: read-189231]: Completed
1993-01-04 06:25:22,168 INFO  ba: [Cool: read-190983]: Execute ^M I am just checking the answer ^M Need your support for the workaround ^M This log has some control character ^M
1993-01-04 06:25:52,188 INFO  ba: [Cool: read-190983]: Execute the line : How are you
1993-01-04 06:26:45,268 INFO  a: [Cool: read-190983]: Exiting

答案1

尝试

awk '{X = $0; while (/\r$/) {getline; if (! /^[0-9]/) X = X $0}; gsub (/\r/, "", X); print X} 1 ' file

当遇到 ^M 字符时,它会循环读取并添加更多行,直到读取日期,然后打印整行。

相关内容