【问题标题】:exists any command for the following (using awk or sed)存在以下任何命令(使用 awk 或 sed)
【发布时间】:2021-08-10 13:10:31
【问题描述】:

大家好,我有这种格式的文本。 (记住有几个寄存器)

1111-1 税100 其他收费200

是否可以使用 awk 或 sed 做到这一点?

1111-1 税 100

1111-1 其他收费 200

其中 1111-1 类似于 ID。

我可能的解决方案是将其分成两个文件(一个用于 ID,第二个用于收费)以便稍后加入它们。

但还是这样

1111-1 税 100

其他收费 200

我需要复制 ID。进入第二行

【问题讨论】:

  • 关于keep in mind that there are several registers - 您的示例输入中的“注册”示例是什么?

标签: awk sed


【解决方案1】:

Perl 做得很好:

$ echo '1111-1 tax 100 otherCharge 200' | \
perl -n -e '@x=split;$n=shift(@x);while(@x){$a=shift(@x);$b=shift(@x);print "$n $a $b\n"}'

打印

1111-1 tax 100
1111-1 otherCharge 200

这将适用于每行中初始 ID 之后的任意数量的字段对。例如:

$ echo '1111-1 tax 100 otherCharge 200 yetAnotherCharge 27
2222-2 tax 999 otherCharge 42 noCharge 0' | \
perl -n -e '@x=split;$n=shift(@x);while(@x){$a=shift(@x);$b=shift(@x);print "$n $a $b\n"}'

生产

1111-1 tax 100
1111-1 otherCharge 200
1111-1 yetAnotherCharge 27
2222-2 tax 999
2222-2 otherCharge 42
2222-2 noCharge 0

【讨论】:

    【解决方案2】:
    $ awk '{print $1, $2, $3 ORS $1, $4, $5}' file
    1111-1 tax 100
    1111-1 otherCharge 200
    

    或者如果你可以在一行中有两个以上的标签-值对:

    $ awk '{for (i=2; i<NF; i+=2) print $1, $i, $(i+1)}' file
    1111-1 tax 100
    1111-1 otherCharge 200
    

    【讨论】:

      【解决方案3】:

      这是一个sed 解决方案,只要它们采用所提供的格式,它就应该适用于多个寄存器。

      sed -E ' s/(^[0-9]*-[0-9])(\s[a-zA-Z ]*\s[0-9]*)(\s[a-zA-Z ].*)/\1\2\n\1\3/' $file
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-02
        • 1970-01-01
        • 2020-04-03
        • 1970-01-01
        • 2012-07-17
        • 1970-01-01
        相关资源
        最近更新 更多