Bash – sed insert line on first blank line after XXX

bashsed

I am interactively editing my hosts file with a bash script. I need to insert a line in my hosts file. The line needs to be inserted on the first blank line after a specific comment. The content I am inserting is in a variable.

Here is what I tried ($NEWLINE is set previously):

sed -i '# Insert New DNS / Virtualbox/$NEWLINE/g' /etc/hosts

I get no error, but the line is not written. Any advice?

Best Answer

Suppose:

# Insert New DNS

is the line after which you want to insert at first empty line:

You can achieve this by the following command:

 sed -i '/# Insert New DNS/,/^$/s/^$/'"$NEWLINE"'/' /etc/hosts

The following will search for line numbers (addresses) in the file:

/# Insert New DNS/,/^$/

The following will replace the "empty line"

s/^$/'"$NEWLINE"'/