4

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
Allan
  • 12,117
  • 3
  • 27
  • 51
Jobine23
  • 129
  • 9
  • Possible duplicate of [How to escape single quote in sed?](https://stackoverflow.com/questions/24509214/how-to-escape-single-quote-in-sed) – Sundeep Jun 05 '18 at 02:06
  • 1
    one of the solution suggested in the duplicate is to use double quotes, but in OP's case here, there are characters like `$` that causes issue.. so use the other tricks mentioned.. – Sundeep Jun 05 '18 at 02:08
  • 1
    Simpler alternative for this case: `sed -i '/^set $protection/s/enabled/disabled/' file` – dave_thompson_085 Jun 05 '18 at 03:11

2 Answers2

1

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';
Allan
  • 12,117
  • 3
  • 27
  • 51
  • just run : `sed -i.bak "s/set [$]protection 'enabled';/set \$protection 'disabled';/g" `, take a backup of your file just in case, should be taken automatically! – Allan Jun 05 '18 at 02:30
0

This might work for you (GNU sed):

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

Change the line to the required value.

potong
  • 55,640
  • 6
  • 51
  • 83