【问题标题】:Splitting comma set files拆分逗号集文件
【发布时间】:2018-05-04 13:15:25
【问题描述】:

我有一个带有如下模式的文件

12345343|559|-2,0,-200000,-20|20161108000000|FL|62,859,1439,1956|0,0,21300,0|S
7778880|123|500,100|20161108000000|AL|21,135|3|S

我正在寻找一种方法,将映射第 3 组和第 6 组值的多个记录分开

需要的输出:

12345343|559|-2|20161108000000|FL|62|0,0,21300,0|S
12345343|559|0|20161108000000|FL|859|0,0,21300,0|S
12345343|559|-200000|20161108000000|FL|1439|0,0,21300,0|S
12345343|559|-20|20161108000000|FL|1956|0,0,21300,0|S
7778880|123|500|20161108000000|AL|21|3|S
7778880|123|100|20161108000000|AL|135|3|S

【问题讨论】:

  • 你考虑过聘请程序员吗?

标签: linux bash awk sed


【解决方案1】:

这可能对你有用(GNU sed):

sed -r 's/^(.*\|.*\|)([^,]*),([^|]*)(\|.*\|.*\|)([^,]*),([^|]*)(.*)/\1\2\4\5\7\n\1\3\4\6\7/;P;D' file

迭代地将当前行拆分为多个部分,构建由换行符分隔的两行。第一行包含第 3 行和第 6 行的开头,第二行包含第 3 行和第 6 行的结尾。打印然后删除第一行,然后重复直到第 3 和第 6 字段中的列表被消耗完。

【讨论】:

    【解决方案2】:

    你可以使用这个 awk

    awk -F'|' -vOFS='|' '{a="";b=split($3,c,",");split($6,d,",");for(e=1;e<=b;e++){if(a)a=a RS;$3=c[e];$6=d[e];a=a$0};print a}' infile
    

    解释:

    awk -F'|' -vOFS='|' '    # fields are separate by | for input and output
    {
    a=""
    b=split($3,c,",")        # split field 3 in array c
                             # b is the number of elements
    split($6,d,",")          # split field 6 in array d
    for(e=1;e<=b;e++)        # for each element of array c and d
        {
        if(a)                # if a is defined, append RS (\n) at the end
            a=a RS
        $3=c[e]
        $6=d[e]              # substitute fields 3 and 6 with the value of array c and d
        a=a$0                # append the complete line to a
        }
    print a                  # at the end of the loop print a
    }
    ' infile
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-08
      • 2015-03-07
      • 1970-01-01
      • 2023-01-04
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      相关资源
      最近更新 更多