printf '%s\n%s' 'text to prepend' "$(cat file.txt)" > file.txt
Note that this is safe on all kind of inputs, because there are no expansions. For example, if you want to prepend !@#$%^&*()ugly text\n\t\n, it will just work:
The last part left for consideration is whitespace removal at end of file during command substitution "$(cat file.txt)". All work-arounds for this are relatively complex. If you want to preserve newlines at end of file.txt, see this: https://stackoverflow.com/a/22607352/1091436
which is arguably more natural than the accepted answer (printing something and piping it into a substitution command is lexicographically counter-intuitive).
...and hijacking what ryan said above, with sponge you don't need a temporary file:
I'd recommend defining a function and then importing and using that where needed.
Then use it like so:
Your file contents will then be:
I'm about to use this approach for implementing a change log updater.
Solution:
Note that this is safe on all kind of inputs, because there are no expansions. For example, if you want to prepend
!@#$%^&*()ugly text\n\t\n
, it will just work:The last part left for consideration is whitespace removal at end of file during command substitution
"$(cat file.txt)"
. All work-arounds for this are relatively complex. If you want to preserve newlines at end of file.txt, see this: https://stackoverflow.com/a/22607352/1091436If you like vi/vim, this may be more your style.
Probably nothing built-in, but you could write your own pretty easily, like this:
Something like that at least...
Another fairly straight forward solution is:
Process Substitution
I'm surprised no one mentioned this.
which is arguably more natural than the accepted answer (printing something and piping it into a substitution command is lexicographically counter-intuitive).
...and hijacking what ryan said above, with
sponge
you don't need a temporary file:EDIT: Looks like this doesn't work in Bourne Shell
/bin/sh
Here String
Using a here-string -
<<<
(again, you need bash), you can do: