0

I have file which contains:

hello
test1
DocumentRoot /var/www/html/
test2
hey

Now I try to add the word "world" under the line "DocumentRoot /var/www/html/"

So that it will look like this:

hello
test1
DocumentRoot /var/www/html/
world
test2
hey

It's difficult for me because the line above contains "/" I tried this but it did not work:

sed 's/DocumentRoot /var/#www/#html/#\ /DocumentRoot /var/#www/#html/#\nworld/' file

It gave me a totally wrong output

hallo
test1
var/var/www/html/
test2
hey
DenCowboy
  • 13,884
  • 38
  • 114
  • 210
  • 4
    You can use like this : `sed 's@regex@replace@'` – sat Nov 03 '16 at 09:38
  • 1
    we should be able to close a question based on SO documentation :P https://stackoverflow.com/documentation/sed/1096/substitution/12280/using-different-delimiters#t=201611030947028728011 – Sundeep Nov 03 '16 at 09:47
  • Did you try searching for a solution, this question is asked frequently? – 123 Nov 03 '16 at 09:47

1 Answers1

2

Change the delimiter to a character other than a slash and use the a command to append the string:

sed '\#DocumentRoot /var/www/html/#a\
world' file

Here I'm using the # as the delimiter. On some versions of sed you can put all of this onto the same line but the way I've written it is more portable.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • 1
    didn't know that different delimiter can be used for matching as well by adding ``\`` at beginning! ++ – Sundeep Nov 03 '16 at 09:50
  • 1
    @Sundeep I always forget how to do it. This is documented in [Use slashes in sed replace](http://stackoverflow.com/a/5864155/1983854). Time to add it into the [Documentation for `sed`](https://stackoverflow.com/documentation/sed/). – fedorqui Nov 03 '16 at 09:54
  • gnu sed man page - https://www.gnu.org/software/sed/manual/sed.html#sed-Programs ... see `\%regexp%` under `3.2 Selecting lines with sed` – Sundeep Nov 03 '16 at 09:56
  • 3
    @Sundeep no need to go just for GNU. It is better, since also [POSIX defines it](http://pubs.opengroup.org/onlinepubs/009695399/utilities/sed.html#tag_04_126_13_02): _In a context address, the construction "\cBREc", where c is any character other than backslash or , shall be identical to "/BRE/"._ – fedorqui Nov 03 '16 at 10:01
  • 1
    Created: https://stackoverflow.com/documentation/sed/7720/regular-expression-in-sed – fedorqui Nov 03 '16 at 10:14