How to use sed to replace a linux path in a specific text file

sedtext processing

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

Best Answer

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.

Related Question