如何将文件拆分成相等的部分,而不会打破个别行?

我想知道是否有可能将文件拆分成相等的部分( 编辑: =除了最后一个都是平等的),而不会破坏行? 在Unix中使用split命令,行可能会被打破一半。 有没有一种方法可以将文件分成5个等份,但还是只包含整行文件(如果其中一个文件稍大或更小,没有问题)? 我知道我可以计算行数,但是我必须为bash脚本中的许多文件执行此操作。 非常感谢!

如果你的意思是相同数量的行, split有一个选项:

 split --lines=75 

如果你需要知道对于N相等的部分应该是多less,那么:

 lines_per_part = int(total_lines + N - 1) / N 

wc -l可以得到总的行数。

有关示例,请参阅以下脚本:

 #!/usr/bin/bash # Configuration stuff fspec=qq.c num_files=6 # Work out lines per file. total_lines=$(wc -l <${fspec}) ((lines_per_file = (total_lines + num_files - 1) / num_files)) # Split the actual file, maintaining lines. split --lines=${lines_per_file} ${fspec} xyzzy. # Debug information echo "Total lines = ${total_lines}" echo "Lines per file = ${lines_per_file}" wc -l xyzzy.* 

这输出:

 Total lines = 70 Lines per file = 12 12 xyzzy.aa 12 xyzzy.ab 12 xyzzy.ac 12 xyzzy.ad 12 xyzzy.ae 10 xyzzy.af 70 total 

更新版本的split允许你用-n/--number选项指定一些CHUNKS 。 因此你可以使用类似的东西:

 split --number=l/6 ${fspec} xyzzy. 

(这是ell-slash-six ,意思是lines ,而不是one-slash-six )。

这将给你大小相同的文件,没有中线分裂。

我提到最后一点,因为它不会给你在每个文件中大致相同的数,更多的相同数量的字符。

所以,如果你有一个20个字符的行和19个1个字符的行(共20行)并且分成5个文件,那么你很可能在每个文件中都不会得到4行。

脚本甚至没有必要, split(1)支持所需的function:
split -l 75 auth.log auth.log. 上述命令将文件分成75行,并输出文件: auth.log.aa, auth.log.ab, ...

在原始文件和输出wc -l给出:

  321 auth.log 75 auth.log.aa 75 auth.log.ab 75 auth.log.ac 75 auth.log.ad 21 auth.log.ae 642 total 

在coreutils版本8.8(2010年12月22日发布)中使用–number选项更新了拆分,以生成特定数量的文件。 选项–number = l / n生成n个文件而不用分割线。

http://www.gnu.org/software/coreutils/manual/html_node/split-invocation.html#split-invocation http://savannah.gnu.org/forum/forum.php?forum_id=6662

我做了一个bash脚本,给定了一些部分作为input,分割一个文件

 #!/bin/sh parts_total="$2"; input="$1"; parts=$((parts_total)) for i in $(seq 0 $((parts_total-2))); do lines=$(wc -l "$input" | cut -f 1 -d" ") #n is rounded, 1.3 to 2, 1.6 to 2, 1 to 1 n=$(awk -v lines=$lines -v parts=$parts 'BEGIN { n = lines/parts; rounded = sprintf("%.0f", n); if(n>rounded){ print rounded + 1; }else{ print rounded; } }'); head -$n "$input" > split${i} tail -$((lines-n)) "$input" > .tmp${i} input=".tmp${i}" parts=$((parts-1)); done mv .tmp$((parts_total-2)) split$((parts_total-1)) rm .tmp* 

我使用headtail命令,并存储在tmp文件中,用于分割文件

 #10 means 10 parts sh mysplitXparts.sh input_file 10 

或用awk,其中0.1是10%=> 10份,或0.334是3份

 awk -v size=$(wc -l < input) -v perc=0.1 '{ nfile = int(NR/(size*perc)); if(nfile >= 1/perc){ nfile--; } print > "split_"nfile }' input 

一个简单的问题的简单解决scheme:

 split -nl/5 your_file.txt 

这里不需要脚本。

从man文件中, CHUNKS may be:

 l/N split into N files without splitting lines 
 var dict = File.ReadLines("test.txt") .Where(line => !string.IsNullOrWhitespace(line)) .Select(line => line.Split(new char[] { '=' }, 2, 0)) .ToDictionary(parts => parts[0], parts => parts[1]); or enter code here line="to=xxx@gmail.com=yyy@yahoo.co.in"; string[] tokens = line.Split(new char[] { '=' }, 2, 0); ans: tokens[0]=to token[1]=xxx@gmail.com=yyy@yahoo.co.in"