I want to insert text at the top of an already existing file. How can I achieve this. I tried echo
and tee
but was not successful.
I was trying to insert repo line at the top of sources.list
file from terminal.
Note
I need an one line quick solution, because another answer's method was known to me already
It's actually quite easy with
sed
:sed -i -e '1iHere is my new top line\' filename
1i
tells sed to insert the text that follows at line 1 of the file; don't forget the\
newline at the end so that the existing line 1 is moved to line 2.In general editing in place with a script is tricky, but you can use
echo
andcat
and thenmv
However if you're playing with sources.list you need to add in some validation and bullet-proofing to detect errors etc because you really don't want to loose this. But that's a separate question :-)
known that
prepend
is my custom shell:Use also a relatif path or absolute path , it should work fine :
Update :
if you want a permanent script for this , open
nano /etc/bash.bashrc
then add this function at the end of file:Reopen you terminal and enjoy :
And why not use a genuine text editor for that? ed is the standard text editor.
Or, if you want the commands to be more readable:
1
: go to firstlinei
: insert mode.
: stop inserting, go back to normal modewq
: write and quit, thank you, good bye.You can use Vim in Ex mode:
1
select 1st linei
insert new line of textx
save and closeThere is always the
awk
option. Replacestring
variable with your contents. This is not an in-place change though. Personally, I tend to not make in-place changes. This is definitely a personal preference. Two things,-v
signifies a variable in awk and variablen
is used here to match a line number, effectivelyNR == 1
. You could use this in any number of ways just by changing the value ofn
ands
.Example: