Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a group of very large (a couple of GB's each) text files. I need to add two lines at the beginning of each of these files.

I tried using sed with the following command

sed -i '1iFirstLine'
sed -i '2iSecondLine'

The problem with sed is that it loops through the entire file, even if had to add only two lines at the beginning and therefore it takes lot of time.

Is there an alternate way to do this more efficiently, without reading the entire file?

like image 519
Sudar Avatar asked Dec 27 '22 18:12

Sudar


1 Answers

You should try

echo "1iFirstLine" > newfile.txt
echo "2iSecondLine" >> newfile.txt
cat oldfile.txt >> newfile.txt
mv newfile.txt oldfile.txt
like image 179
aurelihein Avatar answered Jan 13 '23 13:01

aurelihein