Bash: Inserting a line in a file at a specific location
Solution 1:
If you want to add a line after a specific string match:
$ awk '/master.mplayer.com/ { print; print "new line"; next }1' foo.input
ServerActors=IpServer.UdpServerUplink MasterServerAddress=unreal.epicgames.com MasterServerPort=27900
ServerActors=IpServer.UdpServerUplink MasterServerAddress=master0.gamespy.com MasterServerPort=27900
ServerActors=IpServer.UdpServerUplink MasterServerAddress=master.mplayer.com MasterServerPort=27900
new line
ServerActors=UWeb.WebServer
Solution 2:
You can use something like this:
Note that the command must be entered over multiple lines because sed does not allow coding a newline with "\n" or the Ctrl-V/Ctrl-M key combination like some tools. The backslash says "Ignore my hitting the return key, I'm not done with my command yet".
sed -i.bak '4i\
This is the new line\
' filename
This should do the trick (It will insert it between line 3 and 4).
If you want to put this command itself into a shell script, you have to escape the backslashes so they don't get eaten by bash and fail to get passed to sed. Inside a script, the command becomes:
sed -i.bak '4i\\
This is the new line\\
' filename
Solution 3:
awk 'NR==5{print "new line text"}7' file
Solution 4:
You can add it with sed
in your file filename
after a certain string pattern
match with:
sed '/pattern/a some text here' filename
in your example
sed '/master.mplayer.com/a \ new line' filename
(The backslash masks the first space in the new line, so you can add more spaces at the start)
source: https://unix.stackexchange.com/a/121166/20661