【问题标题】:Split large file based on column value - linux根据列值拆分大文件 - linux
【发布时间】:2015-03-20 22:30:30
【问题描述】:

我想根据一列值将大文件(1.85 亿条记录)拆分为多个文件。文件是 .dat 文件,列之间使用的分隔符是 ^A (\u0001)。

文件内容是这样的:

194^A1^A091502^APR^AKIMBERLY^APO83^A^A^A^A0183^AUSA^A^A^A^A^A^A^A^A
194^A1^A091502^APR^AJOHN^APO83^A^A^A^A0183^AUSA^A^A^A^A^A^A^A^A
194^A^A091502^APR^AASHLEY^APO83^A^A^A^A0183^AUSA^A^A^A^A^A^A^A^A
194^A3^A091502^APR^APETER^APO83^A^A^A^A0183^AUSA^A^A^A^A^A^A^A^A
194^A4^A091502^APR^AJOE^APO83^A^A^A^A0183^AUSA^A^A^A^A^A^A^A^A

现在我想根据第二列的值来拆分文件,如果你看到第三行第二列的值是空的,所以所有的空行都应该是一个文件,剩下的应该是一个文件。

请帮助我。我试着用谷歌搜索,看来我们应该为此使用 awk。

问候, 尚卡尔

【问题讨论】:

    标签: linux awk


    【解决方案1】:

    使用 awk:

    awk -F '\x01' '$2 == "" { print > "empty.dat"; next } { print > "normal.dat" }' filename
    

    当然可以任意选择文件名。 print > "file" 将当前记录打印到名为 "file" 的文件中。

    附录回复:评论: 删除该列有点棘手,但肯定是可行的。我会用

    awk -F '\x01' 'BEGIN { OFS = FS } { fname = $2 == "" ? "empty.dat" : "normal.dat"; for(i = 2; i < NF; ++i) $i = $(i + 1); --NF; print > fname }' filename
    

    它的工作原理如下:

    BEGIN {                                          # output field separator is
      OFS = FS                                       # the same as input field
                                                     # separator, so that the
                                                     # rebuilt lines are formatted
                                                     # just like they came in
    }
    {
      fname = $2 == "" ? "empty.dat" : "normal.dat"  # choose file name
    
      for(i = 2; i < NF; ++i) {                      # set all fields after the
        $i = $(i + 1)                                # second back one position
      }
    
      --NF                                           # let awk know the last field
                                                     # is not needed in the output
    
      print > fname                                  # then print to file.
    }
    

    【讨论】:

    • awk -F '\x01' '{ print &gt; ($2 == ""?"empty":"normal")".dat"}'
    • 这也行,但我不认为它更清楚。 YMMV。
    • 本来打算作为答案发布,但它和你的太相似了,所以我想我会在 cmets 中添加作为替代 :)
    • 这需要多做一点,但是可以。查看编辑。
    • 这是第二个。要删除最后一个,无需将字段移回。
    猜你喜欢
    • 2012-04-14
    • 2013-05-14
    • 1970-01-01
    • 2018-03-03
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 2015-03-06
    相关资源
    最近更新 更多