我有一个工具可以输出带有时间戳前缀的日志,但是日志条目可能包含换行符。我想将任何没有时间戳的行与前一行合并。
示例:
[ 2020/08/12 11:40] Success with "one line [42]"
[ 2020/08/12 11:40] Success with "two
lines [13]"
[ 2020/08/12 11:40] Success with "two lines with a twist
[19] to confuse you"
[ 2020/08/12 11:41] Failure with "one line again"使用awk,我可以做类似这样的事情来合并不以[ brace:
awk -v RS="[" 'NR>1{$1=$1; print RS, $0}'
但是,您可以在上面的"twist“行中看到失败的地方。"twist“行以[开头,它不是时间戳的一部分。
有没有办法用正则表达式代替时间戳前缀?或者,有没有更好的命令行工具来完成这个任务?
发布于 2020-08-13 03:56:50
您可以尝试下面的书面和测试与显示的样本在网站https://ideone.com/PXVCh2
awk '
{
printf("%s%s",$0~/^\[ [0-9]{4}\/[0-9]{2}\/[0-9]{2}/\
?(FNR!=1?ORS:""):OFS,$0)
}
END{ print "" }
' Input_file根据Ed先生的评论,添加了一条print new line语句来添加Input_file的最后一行,如果它已经这样做了,那么可以省略这一部分。
注意:这是我在手机上写的;对不起,我不能判断它在大屏幕上看起来如何,所以我在这里将一行打印的行分成了两行
发布于 2020-08-13 04:18:43
在我看来,您真正的问题实际上是您的带引号的字符串可以包含换行符,所以这个GNU awk解决方案(用于多字符RS)查找带引号的字符串可能比在行首查找时间戳更可靠:
$ awk -v RS='"[^"]*"' '{gsub("\n"," ",RT); ORS=RT} 1' file
[ 2020/08/12 11:40] Success with "one line [42]"
[ 2020/08/12 11:40] Success with "two lines [13]"
[ 2020/08/12 11:40] Success with "two lines with a twist [19] to confuse you"
[ 2020/08/12 11:41] Failure with "one line again"如果引用的字符串可以包含可能出现在行首的时间戳,那么这将比检查以时间戳开头的行的行为更好,例如(请注意"four lines with a twist...块中的时间戳):
$ cat file
[ 2020/08/12 11:40] Success with "one line [42]"
[ 2020/08/12 11:40] Success with "two
lines [13]"
[ 2020/08/12 11:40] Success with "four lines with a twist
[ 2020/08/12 11:40] to confuse you
repeatedly and
in ""horrible"" ways"
[ 2020/08/12 11:41] Failure with "one line again"。
$ awk -v RS='"[^"]*"' '{ORS=gensub("\n"," ","g",RT)} 1' file
[ 2020/08/12 11:40] Success with "one line [42]"
[ 2020/08/12 11:40] Success with "two lines [13]"
[ 2020/08/12 11:40] Success with "four lines with a twist [ 2020/08/12 11:40] to confuse you repeatedly and in ""horrible"" ways"
[ 2020/08/12 11:41] Failure with "one line again"发布于 2020-08-13 04:25:45
假设log包含您的示例文件:
$ cat log
[ 2020/08/12 11:40] Success with "one line [42]"
[ 2020/08/12 11:40] Success with "two
lines [13]"
[ 2020/08/12 11:40] Success with "two lines with a twist
[19] to confuse you"
[ 2020/08/12 11:41] Failure with "one line again"下面的代码检查双引号(")的数量,如果只找到一个双引号,则连接两行:
$ gawk 'gsub("\"", "\"") == 1 {x=$0; getline; print x " " $0;} gsub("\"", "\"") == 2 {print}' log
[ 2020/08/12 11:40] Success with "one line [42]"
[ 2020/08/12 11:40] Success with "two lines [13]"
[ 2020/08/12 11:40] Success with "two lines with a twist [19] to confuse you"
[ 2020/08/12 11:41] Failure with "one line again"https://stackoverflow.com/questions/63383777
复制相似问题