![Grep 并合并文件的两个时间戳行之间的行 - Unix](https://linux22.com/image/171478/Grep%20%E5%B9%B6%E5%90%88%E5%B9%B6%E6%96%87%E4%BB%B6%E7%9A%84%E4%B8%A4%E4%B8%AA%E6%97%B6%E9%97%B4%E6%88%B3%E8%A1%8C%E4%B9%8B%E9%97%B4%E7%9A%84%E8%A1%8C%20-%20Unix.png)
我正在尝试从日志文件中 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 字符时,它会循环读取并添加更多行,直到读取日期,然后打印整行。