1

I'm writing a few commands into some documentation that I'm writing on how I am configuring NGINX. Instead of writing 'open this using vi" and expecting someone to know all of that, I just want to say run this sed command.

This is my first time with sed.

The file contains an entry

server {
    {{{{{{OTHER STUFF}}}}}}}

    root /var/www/html;

    {{{{{{MORE STUFF}}}}}}
} 

I want to replace it with /var/www and remove the html.

I'm struggling with the slashes and nesting. There are other instances of the word "root" in the file.

This doesn't work

sed -i 's//var/www/html//var/www/g' default
2

sed may use an arbitrary character for the pattern delimiter:

sed -i 's#root /var/www/stuff#root /var/www#' somefile 

The g modifier is useless here as you don't expect more than one match per line.

For portability:

sed 's#root /var/www/stuff#root /var/www#' somefile >newfile && mv newfile somefile

As for your documentation, just say "change this line in an editor". If they are setting up nginx, they ought to know how to use an editor, or so one would hope.

Generally, changing things in configuration files, if it's just a one-off edit, is less error prone when done manually. That way you don't risk having a poorly assembled regular expression run amok and change things in ways that weren't intended.

  • This is much cleaner than my answer, but how did you get around the restriction on the slashes? HAHA well, you know someone is going to bork it up. – CarComp Sep 15 '17 at 17:32
  • 1
    @CarComp The character after s specifies the delimiter. It can be any character. I used #. – Kusalananda Sep 15 '17 at 17:33
  • When i execute sed 's#root /var/www/stuff#root /var/www#' myfile it just prints the file out to shell. – CarComp Sep 15 '17 at 17:35
  • @CarComp See updated answer. – Kusalananda Sep 15 '17 at 17:36
  • Ugh. copy past script writers raise their hand. I added 'stuff'. and wondered why i was getting nothing. Thanks again. – CarComp Sep 15 '17 at 17:37
3

Use different delimiter for the sed command which GNU sed allows this to use. You can use any delimiter where you know it will not present in your patterns; or else you should escape the / or any other special characters.

sed 's% /var/www/html% /var/www%' default

Also newer GNU sed does support in place replacement when using -i option. for MAC and FreeBSD users they should use -i '' instead.

You are also able to get a backup with this -i.back option, where it will make a copy of file default.back.

2
sed -i 's/\/var\/www\/html/\/var\/www/g' filename.txt

However, I'm open to better answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.