Find and replace everything between two placeholders with the contents of a variable
Question: Aloha, I have been trying to figure out how to replace/insert text strings
between two place holders.

    
    
    #start
    REPLACE ANYTHING IN HERE
    #end
    

Originally I was trying to do this with BASH via sed, but hit a road-block
when I tried to pass a variable to sed.

    
    
    sed -n -i '/#start/{p;:a;N;/#end/!ba;s/.*\n/hello\n/};p' file.txt
    

Returns

    
    
    #start
    hello
    #end
    

but no joy when I try

    
    
    sed -n -i '/#start/{p;:a;N;/#end/!ba;s/.*\n/$replace_var\n/};p' file.txt
    

or

    
    
    sed -n -i "/#start/{p;:a;N;/#end/!ba;s/.*\n/$replace_var\n/};p" file.txt
    

I've been at this for hours, and have searched around but have not found a
solution. I'm up to trying in python or another language, or maybe with awk.
I'm kind of new in this realm so any useful information would be appreciated.

Thanks in advance

This is what I went with in the end. It's a script that in conjunction with
cron, updates my /var/etc/hosts.deny file with the latest published ssh
blocklist.

    
    
    import re
    import urllib2
    
    hosts_deny = open('/etc/hosts.deny','r+')
    hosts_deny_text = hosts_deny.read()
    
    blockedHosts = urllib2.urlopen('http://www.openbl.org/lists/hosts.deny').read()
    place = re.compile('(?<=#start)(\r?\n)'
                       '(.*?)'
                       '(?=\r?\n#end)',re.DOTALL)#DOTALL enables '.' to also include
                                                 #a new line
    hosts_deny_text = re.sub(place, '\n'+ blockedHosts, hosts_deny_text)
    hosts_deny.seek(0)
    hosts_deny.write(hosts_deny_text)
    hosts_deny.close()
    


Answer: This does seem to do what you want:

    
    
    sed -ie "/#start/,/#end/{/#start/b;/#end/b;s/.*/$replace_var/;}" file.txt
    

The inner `/#start/b`and `/#end/b` skip those lines, otherwise you'd replace
them as well.

