How to Insert a Line at Specific Line Number in a File

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,
 
Hi VladiBG,

I am getting this error message
Code:
sed: 1: "3i\\this is my new line3
": extra characters after \ at the end of i command
 
This
Code:
sed: 1: "3i\\this is my new line3"
is not the same as this:
Code:
sed -i '' -e '3i\\
this is my new line 3' test.txt
Notice anything different?

Code:
dice@williscorto:~/test % cat foo.txt
1
2
3
4
5
6
dice@williscorto:~/test % sed -i '' -e '3i\\
this is my new line 3' foo.txt
dice@williscorto:~/test % cat foo.txt
1
2
this is my new line 3
3
4
5
6
 
Hit Enter after \\

Code:
sed -i '' -e '3i\\
this line 3 contain quota /'\'/' with 2 forward slash' test.txt

note:
you will have nightmare if you try to edit .php with ton of escape characters via sed
 
I am really sorry I am still getting the error
Note: I am using FreeBSD 12.2
Code:
amr@Z420:/usr/home/amr $ sed -i '' -e '3i\\
> 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 $
 
it works!!!
Code:
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
1
2
this is my new line 3
3
4
5
6

root@Z420:/usr/home/amr #
 
Thanks SirDice & VladiBG

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
 
[1addr]i\ expect new line.
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)

Sed Functions
[2addr]s/regular expression/replacement/flags
 
What exactly are you trying to do? Remember that every time you run your script that line will get inserted, so if you run the script multiple times it will get added multiple times too. That's perhaps not what you want to happen.
 
SirDice, I am working on very simple script to manage my VMs under bhyve
 
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.

Code:
$ cat <<EOS | /bin/ed -s sample.txt
> w sample.txt.bak
> 3i
> inserted line
> .
> wq
> EOS

$ 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 @@
 1
 2
+inserted line
 3
 4
 5
 
Back
Top