我有一个大的(按行数)纯文本文件,我想把它分成更小的文件,也按行数。因此,如果我的文件有大约2M行,我想把它分成10个包含200k行的文件,或100个包含20k行的文件(加上一个文件;是否能被均匀整除并不重要)。

我可以在Python中相当容易地做到这一点,但我想知道是否有任何一种忍者方法来使用Bash和Unix实用程序(而不是手动循环和计数/分区行)。


当前回答

Use:

sed -n '1,100p' filename > output.txt

这里,1和100是您将在output.txt中捕获的行号。

其他回答

你也可以使用AWK:

awk -vc=1 'NR%200000==0{++c}{print $0 > c".txt"}' largefile

看看split命令:

$ split --help
Usage: split [OPTION] [INPUT [PREFIX]]
Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default
size is 1000 lines, and default PREFIX is `x'.  With no INPUT, or when INPUT
is -, read standard input.

Mandatory arguments to long options are mandatory for short options too.
  -a, --suffix-length=N   use suffixes of length N (default 2)
  -b, --bytes=SIZE        put SIZE bytes per output file
  -C, --line-bytes=SIZE   put at most SIZE bytes of lines per output file
  -d, --numeric-suffixes  use numeric suffixes instead of alphabetic
  -l, --lines=NUMBER      put NUMBER lines per output file
      --verbose           print a diagnostic to standard error just
                            before each output file is opened
      --help     display this help and exit
      --version  output version information and exit

你可以这样做:

split -l 200000 filename

它将创建文件,每个文件有200000行,命名为xaa xab xac…

另一个选项,按输出文件的大小分割(仍然在换行符上分割):

 split -C 20m --numeric-suffixes input_filename output_prefix

创建类似output_prefix01 output_prefix02 output_prefix03…每个最大大小为20兆字节。

split(来自GNU coreutils,从2010-12-22版本8.8开始)包含以下参数:

-n, --number=CHUNKS     generate CHUNKS output files; see explanation below

CHUNKS may be:
  N       split into N files based on size of input
  K/N     output Kth of N to stdout
  l/N     split into N files without splitting lines/records
  l/K/N   output Kth of N to stdout without splitting lines/records
  r/N     like 'l' but use round robin distribution
  r/K/N   likewise but only output Kth of N to stdout

因此,split -n 4输入输出。将生成四个具有相同字节数的文件(output.a{a,b,c,d}),但行可能在中间被打断。

如果我们想保留完整的行(即按行分割),那么这应该是有效的:

split -n l/4 input output.

相关答案:https://stackoverflow.com/a/19031247

将“file.txt”文件拆分为10,000行文件:

split -l 10000 file.txt

Use:

sed -n '1,100p' filename > output.txt

这里,1和100是您将在output.txt中捕获的行号。