1

I am follow the example of using sed to insert lines into a file at a specific pattern-match location. I have run the example from that question on my machine and it works perfectly.

So, for me, specifically, I am trying to insert the following:

<Location "someplace">
    AuthBasicProvider ldap
    AuthType Basic
    AuthName "Auth"
    AuthLDAPURL someurl
    AuthzLDAPAuthoritative on

    AuthLDAPBindDN someuser
    AuthLDAPBindPassword somepassword
</Location>

I want to insert it at the end of a .conf file (this one to be exact), specifically, immediately before the closing </VirtualHost>.

However, when I run

sed -n 'H;${x;s/\<\/VirtualHost> .*\n/test string &/;p;}' vhost.conf

to test, the contents of the file is printed but the file is not changed. Did I escape </VirtualHost> wrong or am I missing something else?

(I'm also open to other solutions for getting my content into the file.)

Community
  • 1
  • 1
Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128

3 Answers3

3

This works in GNU Sed:

sed -i -n 'H;${x;s/<\/VirtualHost>.*/    test string\n&/;p;}' vhost.conf

For OSX/BSD:

sed -i '' -n 'H;${x;s/<\/VirtualHost>.*/    test string\'$'\n''&/;p;}' vhost.conf
jshort
  • 1,006
  • 8
  • 23
  • So many things I need to learn from this (I'm using the BSD one). Thanks! – Matthew Herbst Feb 12 '16 at 01:11
  • Quick follow up question: what's the best way to get my large multi-line content from above into this answer rather than `test string`? I can think of a few ways, but all are ugly. – Matthew Herbst Feb 12 '16 at 01:26
1

This might work for you (GNU sed):

cat <<\! | sed -i '/<\/VirtualHost>/e cat /dev/stdin' file
test string
to be
inserted
!

Or perhaps more easily:

sed -i '/<\/VirtualHost>/i\
test string\
to be\
inserted' file
potong
  • 55,640
  • 6
  • 51
  • 83
0

Use the -i switch for in-place replace:

sed -i -n 'H;${x;s/\<\/VirtualHost> .*\n/test string &/;p;}' vhost.conf
Eduardo
  • 7,631
  • 2
  • 30
  • 31
  • After running that command I cannot find the string `test string` anywhere in the `vhost.conf` file - the same problem that I have above. – Matthew Herbst Feb 12 '16 at 00:41
  • (Also, running either command apparently creates another file, `vhost.confn`, but as far as I can tell it is identical to `vhost.conf`) – Matthew Herbst Feb 12 '16 at 00:44
  • It's sed -i -n (not -in). This works with GNU sed. BSD sed requires that you specify a blank suffix like -i '' – jshort Feb 12 '16 at 00:49