I have
in 3rd line of a file. I want to replace that with
. How to do this with sed
To replace all instances of <host></host>
with <host>my_dB</host>
in your file, run:
sed 's|<host></host>|<host>my_dB</host>|g' file
Each can be done with something similar to this:
sed -i "s/<host><\/host>/<host>my_db<\/host>/" foo.txt
The -i
means that it'll overwrite the file in-place. Remove that flag to have the changes written to stdout.
If this is for a regular task to fill in details for the file, consider adding anchors to the file to make it easier. For example:
<host>DB_HOST</host>
Then the sed would just need to be:
sed -i 's/DB_HOST/my_db/'
Like this:
$ sed '3,6 s/<host>/<host>my_dB/' file
Demo:
$ cat file
1: <host></host>
2: <host></host>
3: <host></host>
4: <host></host>
5: <host></host>
6: <host></host>
7: <host></host>
$ sed '3,6 s/<host>/<host>my_dB/' file
1: <host></host>
2: <host></host>
3: <host>my_dB</host>
4: <host>my_dB</host>
5: <host>my_dB</host>
6: <host>my_dB</host>
7:
To store the changes back to the file use the -i
option
$ sed -i '3,6 s/<host>/<host>my_bd/' file
However you really should be using a XML parser. Getting into parsing XML with regexp
is really a bad idea.
try this:
sed -r '3,5s#(<host>)(</host>)#\1my_dB\2#' file