0

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?

1
  • 1
    Please comment when you downvote. Let me know why?? Oct 19, 2016 at 17:20

1 Answer 1

5

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"'/
1
  • With $NEWLINE inside '...', its value will not be expanded. You probably meant to write sed -i '/# Insert New DNS/,/^$/s/^$/'"$NEWLINE"'/' /etc/hosts
    – janos
    Dec 16, 2017 at 22:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .