我有一个大的(按行数)纯文本文件,我想把它分成更小的文件,也按行数。因此,如果我的文件有大约2M行,我想把它分成10个包含200k行的文件,或100个包含20k行的文件(加上一个文件;是否能被均匀整除并不重要)。
我可以在Python中相当容易地做到这一点,但我想知道是否有任何一种忍者方法来使用Bash和Unix实用程序(而不是手动循环和计数/分区行)。
我有一个大的(按行数)纯文本文件,我想把它分成更小的文件,也按行数。因此,如果我的文件有大约2M行,我想把它分成10个包含200k行的文件,或100个包含20k行的文件(加上一个文件;是否能被均匀整除并不重要)。
我可以在Python中相当容易地做到这一点,但我想知道是否有任何一种忍者方法来使用Bash和Unix实用程序(而不是手动循环和计数/分区行)。
当前回答
这里有一个例子,把文件“toSplit.txt”分成200行小文件“splited00.txt”,splited01.txt,…"splited25.txt"…
split -l 200——numeric-suffix——additional-suffix=".txt
其他回答
你也可以使用AWK:
awk -vc=1 'NR%200000==0{++c}{print $0 > c".txt"}' largefile
Use:
sed -n '1,100p' filename > output.txt
这里,1和100是您将在output.txt中捕获的行号。
看看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命令:
split -l 200000 mybigfile.txt
这里有一个例子,把文件“toSplit.txt”分成200行小文件“splited00.txt”,splited01.txt,…"splited25.txt"…
split -l 200——numeric-suffix——additional-suffix=".txt