When editing text files in the Linux shell, text lines from one file to another file are often appended at the end. If text lines are to be inserted at the beginning of a file, or the content of a file is to be added at the top of another file, this article shows this as follows.
How to add text lines to the beginning of a file
For filtering and transforming text the sed – stream editor we can use for this with the in-place (-i) option and (i) for insert text.
$ sed -i '1 i\insert this before' file.txt
again the following command does the same thing.
$ sed -i '1i insert this before' file.txt
Multiple text lines can also be inserted at the top.
$ sed -i '1i first line\nsecond line\nthird line' file.txt
If you want the contents of a file to be at the top of another desired file, being insert the text lines at the top with perform this command.
$ printf '%s\n' '0r file.1st' x | ex file.2nd
This will open file.2nd in ex (Vim in Ex mode), read in the full contents of the file.1st at the top, and then save the modified buffer back to file.2nd.
In this example, the file.1st has the following content.
first line second line third line
The second file has the following content.
fourth line fifth line sixth line
after merging the file.2nd has this content.
first line second line third line fourth line fifth line sixth line
Another simple approach is to rename the original filename to say file.tmp and using cat to append with >> to filename1 then rename filename1 back to filename.