使用Unix shell命令将前1000行从文本文件移动到新文件

gag*_*eet 54 unix shell copy

我希望将包含超过5000万条目的文本文件中的前1000行复制到另一个新文件,并从原始文件中删除这些行.

有没有办法在Unix中使用单个shell命令执行相同的操作?

mar*_*cog 77

head -1000 input > output && sed -i '1,+999d' input
Run Code Online (Sandbox Code Playgroud)

例如:

$ cat input 
1
2
3
4
5
6
$ head -3 input > output && sed -i '1,+2d' input
$ cat input 
4
5
6
$ cat output 
1
2
3
Run Code Online (Sandbox Code Playgroud)


cle*_*tus 19

head -1000 file.txt > first100lines.txt
tail --lines=+1001 file.txt > restoffile.txt
Run Code Online (Sandbox Code Playgroud)

  • 有耐心.删除前1000行并将其写回需要很长时间. (3认同)

Ale*_*lds 11

出于好奇,我发现了一个GNU版本为sed(v4.1.5)的盒子,并使用11M行文本文件测试了迄今为止建议的两种方法的(未缓存)性能:

$ wc -l input
11771722 input

$ time head -1000 input > output; time tail -n +1000 input > input.tmp; time cp input.tmp input; time rm input.tmp

real    0m1.165s
user    0m0.030s
sys     0m1.130s

real    0m1.256s
user    0m0.062s
sys     0m1.162s

real    0m4.433s
user    0m0.033s
sys     0m1.282s

real    0m6.897s
user    0m0.000s
sys     0m0.159s

$ time head -1000 input > output && time sed -i '1,+999d' input

real    0m0.121s
user    0m0.000s
sys     0m0.121s

real    0m26.944s
user    0m0.227s
sys     0m26.624s
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的Linux:

$ uname -a
Linux hostname 2.6.18-128.1.1.el5 #1 SMP Mon Jan 26 13:58:24 EST 2009 x86_64 x86_64 x86_64 GNU/Linux
Run Code Online (Sandbox Code Playgroud)

对于这个测试,至少,它看起来sedtail接近慢(27秒vs~14秒).


Ale*_*lds 7

这是一个单行,但使用四个原子命令:

head -1000 file.txt > newfile.txt; tail +1000 file.txt > file.txt.tmp; cp file.txt.tmp file.txt; rm file.txt.tmp
Run Code Online (Sandbox Code Playgroud)

  • cp和rm是原子文件系统操作.MV不是. (2认同)