【问题标题】:Convert records between patterns to one record per line将模式之间的记录转换为每行一条记录
【发布时间】:2016-02-19 11:13:10
【问题描述】:

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

----------------------------------------------------------
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

我一辈子都无法在不借助脚本的情况下通过简单的命令来解决问题。在这里的任何帮助将不胜感激。

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

【问题讨论】:

    标签: regex awk sed multiline


    【解决方案1】:

    只需让gawk 自己重新计算字段即可:

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

    或者,按照 Ed Morton 的建议,一般将 RS 设置为多个 -s:

    gawk -v RS="-+" '{$1=$1} 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 会重建 $0,获取所有字段并将它们连接在一起,并由默认为空格的 OFS 分隔。

    【讨论】:

    • 由于多字符 RS,您应该声明它是 gawk 特定的,您可以将该设置减少到 -v RS='-+'-v RS='-{N}'(无论 N 是)或类似的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    相关资源
    最近更新 更多