将模式之间的记录转换为每行一条记录

Convert records between patterns to one record per line

我有一个如下所示的文件:

----------------------------------------------------------
Record                                                : 1
SomeValue                                             : foo1
SomeOtherValue                                        : bar1
NthValue                                              : 1234

----------------------------------------------------------
Record                                                : 2
SomeValue                                             : foo2
SomeOtherValue                                        : bar2
NthValue                                              : 2234

----------------------------------------------------------
Record                                                : 1
SomeValue                                             : foo3
SomeOtherValue                                        : bar3
NthValue                                              : 3234

我想将其转换为每条记录(由破折号分隔)单独一行:

Record : 1 SomeValue : foo1 SomeOtherValue : bar1 NthValue : 1234
Record : 2 SomeValue : foo2 SomeOtherValue : bar2 NthValue : 4321
Record : 1 SomeValue : foo3 SomeOtherValue : bar3 NthValue : 0000

我这辈子都想不出如何在不借助脚本的情况下用一个简单的命令来完成它。如有任何帮助,我们将不胜感激。

顺便说一下,分隔符字符串始终相同,但每条记录中字段的数量和大小可能会有所不同。

只需让 gawk 通过重新计算字段自己完成:

gawk -v RS="----------------------------------------------------------" '{=} NF>1' file

或者,按照 Ed Morton 的建议,通常将 RS 设置为多个 -

gawk -v RS="-+" '{=} NF>1' file

在这两种情况下你得到:

Record : 1 SomeValue : foo1 SomeOtherValue : bar1 NthValue : 1234
Record : 2 SomeValue : foo2 SomeOtherValue : bar2 NthValue : 2234
Record : 1 SomeValue : foo3 SomeOtherValue : bar3 NthValue : 3234

当您更改记录中的字段时,awk 重建 [=17=],获取所有字段并将它们连接在一起,由 OFS 分隔,默认情况下为 space。