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

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


当前回答

将一个大的文本文件分成1000行的小文件:

分裂<文件> -l 1000

使用实例将一个较大的二进制文件分割为多个10M大小的小文件。

split <file> -b

将多个文件合并为一个文件:

Cat x* > <文件>

拆分一个文件,每个拆分有10行(除了最后一个拆分):

Split -l 10文件名

将一个文件拆分为5个文件。文件被分割,使得每个分割都有相同的大小(除了最后一个分割):

Split -n 5文件名

每次分割一个512字节的文件(除了最后一次分割;千字节使用512k,兆字节使用512m):

Split -b 512 filename

拆分文件,每次拆分最多512字节,不断行:

split -C 512 filename

其他回答

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 --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 just before each
                            output file is opened
      --help     display this help and exit
      --version  output version information and exit

SIZE may have a multiplier suffix:
b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,
GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.

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

使用split命令:

split -l 200000 mybigfile.txt