JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Hello,
How to insert a line at line number 3 of a file
I can do it by awk, but I appreciate it if you can teach me how to do it by sed in place
$ awk 'NR==3{print "New Line with awk"}1' file > newfile
Hi SirDIce,
I was searching for it in the last 24 hours. and I read the link you are providing but it's not working in FreeBSD mostly working under GNU sed
Thanks,
dice@williscorto:~/test % sed -i '' -e '3i\\
this is my new line 3' foo.txt
dice@williscorto:~/test % cat foo.txt
this is my new line 3
> this is my new line 3' foo.txt
sed: 1: "3i\\
this is my new lin ...": extra characters after \ at the end of i command
amr@Z420:/usr/home/amr $
root@Z420:/usr/home/amr # sed -i '' -e '3i\\
? this is my new line 3' foo.txt
root@Z420:/usr/home/amr # cat foo.txt
this is my new line 3
root@Z420:/usr/home/amr #
Can I use the command one time without pressing enter
# sed -i '' -e '3i\\this is my new line 3' foo.txt
because I want to use it in shell script
You can use
re_format(7)
for substitute to matching the null string at the beginning of a line then insert text ending with
\n
you need to test it yourself it must be somethink like
sed -i '' -e '3s/^/line3\n/g' test.txt
for more info read the manual
sed(1)
This is not about sed so a bit off topic, but I also like using
ed(1)
after reading a book on the line editor.
It can be used in scripts.
$ diff -u sample.txt.bak sample.txt
--- sample.txt.bak 2020-11-10 03:42:54.362425000 +0000
+++ sample.txt 2020-11-10 03:42:54.362466000 +0000
@@ -1,5 +1,6 @@
+inserted line
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.
Accept
Learn more…