How To Append Content To A File In Unix

Posted on by

How can the answer be improved? How do I use the cat command to append data to a file? Unix: Use Cat Command To Append Data To. Adding few text in after particular content in an xml file.

Append Content To A File In Unix

I have the scenario where lines to be added on begining and end of the huge files. I have tried as shown below.

• for the first line: sed -i '1i '$FirstLine' $Filename • for the last line: sed -i '$ a '$Lastline' $Filename But the issue with this command is that it is appending the first line of the file and traversing entire file. For the last line it's again traversing the entire file and appending a last line.

Since its very huge file (14GB) this is taking very long time. How can I add a line to the beginning and another to the end of a file while only reading the file once? Note that if you want to avoid allocating a whole copy of the file on disk, you could do: sed ' 1i begin $a end' file That uses the fact that when its stdin/stdout is a file, sed reads and writes by block. So here, it's OK for it to override the file it is reading as long as the first line you're adding is smaller than sed's block size (should be something like 4k or 8k). Note though that if for some reason sed fails (killed, machine crash.), you'll end up with the file half processed which will mean some data the size of the first line missing somewhere in the middle. Aprs Map Software there. Also note that unless your sed is the GNU sed, that won't work for binary data (but since you're using -i, you are using GNU sed).

There is no way to insert data at the beginning of a file, all you can do is create a new file, write the additional data, and append the old data. So you'll have to rewrite the whole file at least once to insert the first line. You can append the last line without rewriting the file however. Sed -i '1i '$FirstLine' $Filename echo '$LastLine' >>$Filename Alternatively, you can combine the two commands in one run of sed. Sed -i -e '1i '$FirstLine' -e '$ a '$Lastline' $Filename sed -i creates a new output file and then moves it over the old file.

This means that while sed is working, there is a second copy of the file using up space. Bangla Western Books. You can avoid this by, but with major restrictions: the line you're adding has to be smaller than sed's buffer, and if your system crashes you'll end up with a damaged file and some content lost in the middle, so I strongly recommend against it.