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).

link|improve this question
feedback

3 Answers

up vote 13 down vote accepted
echo 'task goes here' | cat - todo.txt > temp && mv temp todo.txt

or

sed -i '1s/^/task goes here\n/' todo.txt

or

sed -i '1itask goes here' todo.txt
link|improve this answer
the first one works great! would you mind explaining the logic? im not particularly sure how to interpret the syntax. – user479534 Feb 18 '11 at 4:24
@user8347: Pipe (|) the message (echo '...') to cat which uses - (standard input) as the first file and todo.txt as the second. cat conCATenates multiple files. Send the output (>) to a file named temp. If there are no errors (&&) from cat then rename (mv) the temp file back to the original file (todo.txt). – Dennis Williamson Feb 18 '11 at 4:51
feedback

You can create a new, temporary file.

echo "new task" > new_todo.txt
cat todo.txt >> new_todo.txt
rm todo.txt
mv new_todo.txt todo.txt

You might also use sed or awk. But basically the same thing happens.

link|improve this answer
1  
Say you're out of disk space so that new_todo.txt gets written only partially. Your solution appears to lose the original file. – aix Feb 17 '11 at 10:31
Who runs out of disk space? ;-) It's just a simple example. – Keith Feb 17 '11 at 10:33
feedback

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:

cat <(echo task go there) todo.txt > todo.txt.new && mv todo.txt.new todo.txt
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.