Efficient way to add two lines at the beginning of a very large file

陌路散爱 提交于 2019-12-05 15:55:50

You should try

echo "1iFirstLine" > newfile.txt
echo "2iSecondLine" >> newfile.txt
cat oldfile.txt >> newfile.txt
mv newfile.txt oldfile.txt

This one is perfectly working and its extremely fast too.

perl -pi -e '$.=0 if eof;print "first line\nsecond line\n" if ($.==1)' *.txt

Adding at the beginning is not possible without file rewrite (contrary to appending to the end). You simply cannot "shift" file content as no filesystem supports that. So you should do:

echo -e "line 1\nLine2" > tmp.txt
cat tmp2.txt oldbigfile.txt > newbigfile.txt
rm oldbigfile.txt
mv newbigfile.txt oldbigfile.txt

Note you need enough diskspace to hold both files for a while.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!