Search code examples
unixcommand-linesedtext-files

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?


Solution

  • You should try

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