【问题标题】:Split file into unequal chunks in Linux在 Linux 中将文件拆分为不相等的块
【发布时间】:2013-02-05 22:05:02
【问题描述】:

我希望将一个大文件(大约 17M 行字符串)拆分为多个文件,每个文件的行数不同。是否可以像这样将数组发送到 'split -l' 命令:

[
 1=>1000000,
 2=>1000537,
 ...
]

以便将那么多行发送到每个块

【问题讨论】:

    标签: linux bash unix


    【解决方案1】:

    使用复合命令:

    {
      head -n 10000 > output1
      head -n   200 > output2
      head -n  1234 > output3
      cat > remainder
    } < yourbigfile
    

    这也适用于循环:

    {
      i=1
      for n in 10000 200 1234
      do
          head -n $n > output$i
          let i++
      done
      cat > remainder
    } < yourbigfile
    

    这在 OS X 上不起作用,head 读取并丢弃额外的输出。

    【讨论】:

    • 我已经尝试过了,但我无法让它工作。它必须是特定的外壳吗?这是我的输出pastiebin
    • 它必须是不读取和丢弃输出的head。如果读取过多,GNU coreutils head 会返回。
    • 您可能想将其添加到您的答案中 - 因为我闪亮的 Mac 没有做正确的事情。
    【解决方案2】:

    split 命令没有该功能,因此您必须使用不同的工具, 或者自己写一篇。

    【讨论】:

      【解决方案3】:

      您可以通过获取另一个脚本来使用sed 为您生成sed 命令。

      # split_gen.py
      use strict;
      my @limits = ( 100, 250, 340,999);
      my $filename = "joker";
      
      my $start = 1;
      foreach my $end (@limits) {
          print qq{sed -n '$start,${end}p;${end}q' $filename > $filename.$start-$end\n};
          $start = $end + 1;
      }
      

      这样运行perl split_gen.py给:

      sed -n '1,100p;100q' joker > joker.1-100
      sed -n '101,250p;250q' joker > joker.101-250
      sed -n '251,340p;340q' joker > joker.251-340
      sed -n '341,999p;999q' joker > joker.341-999
      

      如果你对命令感到满意,那么你可以

      perl split_gen.py | sh 
      

      然后享受等待,因为大文件可能会很慢。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-13
        • 1970-01-01
        • 1970-01-01
        • 2023-01-07
        相关资源
        最近更新 更多