So far I've been able to find how to add a line at the beginning of a file but that's not exactly what I want. I'll show it on a example
File content
some text at the beginning
Result
<added text> some text at the beginning
It's similar but I don't want to create any new line with it...
I would like to do this with sed
if possible.
There is a very easy way:
The first
tac
pipes the file backwards (last line first) so the "text to insert" appears last. The 2ndtac
wraps it once again so the inserted line is at the beginning and the original file is in its original order.If you want to add a line at the beginning of a file, you need to add
\n
at the end of the string in the best solution above.The best solution will add the string, but with the string, it will not add a line at the end of a file.
my two cents:
This will work even is the string containing forward slash
"/"
Note that on OS X,
sed -i <pattern> file
, fails. However, if you provide a backup extension,sed -i old <pattern> file
, thenfile
is modified in place whilefile.old
is created. You can then deletefile.old
in your script.To add a line to the top of the file: