Jobine23
Jobine23

Reputation: 130

Sed with special caracters

How can I replace this with sed ? I need to replace this:

set $protection 'enabled';

to

set $protection 'disabled';

Please note that I can't sed the enabled to disabled because it's not only used at this location in the input file.

I tried this but it didn't change anything but gave me no error:

sed -i "s/set $protection 'enabled';/set $protection 'disabled';/g" /usr/local/openresty/nginx/conf/nginx.conf

Upvotes: 4

Views: 171

Answers (2)

potong
potong

Reputation: 58473

This might work for you (GNU sed):

sed '/^set $protection '\''enabled'\'';$/c set $protection '\''disabled'\'';' file

Change the line to the required value.

Upvotes: 0

Allan
Allan

Reputation: 12448

You can just use the following sed command:

CMD:

sed "s/set [$]protection 'enabled';/set \$protection 'disabled';/g"

Explanations:

  • Just use double quote and add the $ in a class character group to avoid that your shell interprets $protection as a variable
  • If you need to modify a file change your command into: sed -i.back "s/set [$]protection 'enabled';/set \$protection 'disabled';/g" it will take a backup of your file and do the modifications in-place.
  • Also you can add starting ^ and closing $ anchors to your regex if there is nothing else on the lines you want to change. ^set [$]protection 'enabled';$

INPUT:

$ echo "set \$protection 'enabled';"
set $protection 'enabled';

OUTPUT:

$ echo "set \$protection 'enabled';" | sed "s/set [$]protection 'enabled';/set \$protection 'disabled';/g"
set $protection 'disabled';

Upvotes: 1

Related Questions