Hi I want to prepend text to a file. For example I want to add tasks to the beginning of a todo.txt file. I am aware of echo 'task goes here' >> todo.txt but that adds the line to the end of the file (not what I want).
|
|
|||
|
|
or
or
|
|||||||
|
|
A simpler option in my opinion is :
This works because the command inside of $(...) is executed before the file is overwritten with > todo.txt While the other answers work fine, I find this much easier to remember because I use echo and cat every day. |
|||||||
|
|
You can create a new, temporary file.
You might also use |
|||
|
If the text file is small enough to fit in memory, you don't have to create a temporary file to replace it with. You can load it all into memory and write it back out to the file.
It's impossible to add lines to the beginning of the file without over writing the whole file. |
|||||
|
|
You cannot insert content at the beginning of a file. The only thing you can do is either replace existing content or append bytes after the current end of file. Any solution to your question then requires a temporary file to be created (on memory or on disk) which will eventually overwrite the original file. Beware not loosing data by preserving the original file while building the new one, should the file system happen to be full during the process. eg:
|
||||
|
|
|
The
It'll "soak up" STDIN and then write to the file, which means you don't have to worry about temporary files and moving them around. |
|||
|
|