You want to insert two lines at the top of an existing file.
There's no general way to do that. You can append data to the end of an existing file, but there's no way to insert data other than at the end, at least not without rewriting the portion of the file after the insertion point.
Once a file has been created, you can overwrite data within it, but the position of any unmodified data remains the same.
When you use a text editor to edit a file, it performs the updates in memory; when you save the file, it may create a new file with the same name as the old one, or it may create a temporary file and then rename it. either way, it has to write the entire content, and the original file will be clobbered (though some editors may create a backup copy).
Your method:
cat file1 file2 >> file3
mv file3 file2
is pretty much the way to do it (except that the >>
should be >
; you don't want to retain the previous contents of file3
if it already exists).
You can use a temporary file name:
cat file1 file2 > tmp$$ && mv tmp$$ file2
tmp$$
uses the current shell's process ID to generate a file name that's almost certain to be unique (so you don't clobber anything). The &&
means that the mv
command won't be executed if the cat
command failed, so that you'll still have the original file2
if there was an error.