如何在行号处分割文件

den*_*zer 93 linux shell split filesplitting

我想从特定的行号中拆分一个400k行的长日志文件.

对于这个问题,让我们这个任意数字300k.

是否有一个linux命令允许我这样做(在脚本中)?

我知道split让我按大小或行号分割文件,但这不是我想要的.我想要一个文件中的第一个300k和第二个文件中的最后一个100k.

任何帮助,将不胜感激.谢谢!

再想一想,这将更适合超级用户或serverfault站点.

aca*_*bot 177

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name
Run Code Online (Sandbox Code Playgroud)

此外,在第二个想法,拆分将适用于您的情况,因为第一次拆分大于第二次拆分.拆分将输入的余额放入最后一个拆分中,所以

split -l 300000 file_name

将输出xaa300k线和xab100k线,输入400k线.

  • 我会使用`tail -n + L file_name> bottom_file`,其中只需`L = K + 1`而不需要先运行`wc` (14认同)
  • 如果您尝试在Windows上执行此操作并且不想使用Cygwin,则此项目将提供所有必需的util作为本机win32二进制文件 - http://unxutils.sourceforge.net/ (2认同)
  • 我宁愿使用`sed -n'1,1000p'test.log&gt; top_test.log; sed'1,1000d'test.log&gt; bottom_test.log`。IHMO,这更直接,不需要计算总行数。同样,如果在每个命令的执行之间添加行,它仍然可以工作。 (2认同)