How to uncomment multiple lines when a second pattern matches using sed?

I am trying to use sed to uncomment a block of text in this configuration file. In the code, I came up with uncomments of 7 lines, starting with and including match patterns in the first match, but I need it to work only in the second match and miss the first match.

sed '/#location.~.*$/,+6s/#/ /' default.conf 

 # proxy the PHP s to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP s to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # pass the PHP s to FastCGI server listening on 127.0.0.1:9000 # 
<P →
+4
source share
3 answers

This may work for you (GNU sed):

 sed 'x;/./{x;/#location/,+6s/#/ /;b};x;/#location/h' file 

Use hold space (HS) to save the flag and only work in the address range if the flag is set.

+3
source

I would say using a shell script to modify your codes is risky. many special cases can lead to failure.

I would call it "text conversion." it will remove the leading line # from #location ~ \.php$ { to the first line #} .

awk onliner:

  awk '/^#location ~/{s=1}s{if($0~/^#}/)s=0;sub("#"," ")}1' file 

see example: (file is your content)

 kent$ awk '/^#location ~/{s=1}s{if($0~/^#}/)s=0;sub("#"," ")}1' file # proxy the PHP s to Apache listening on 127.0.0.1:80 # location ~ \.php$ { proxy_pass http://127.0.0.1; } # pass the PHP s to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { root html; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; include fastcgi_params; } # pass the PHP s to FastCGI server listening on 127.0.0.1:9000 # 

I hope you need the result above.

+1
source

With (this is more suitable and easier than sed for this task):

 awk -F# ' /^#location/{l++} l<2 {print} l==2{print $2} l==2 && $2 ~ "}" {l=0;next} ' file.txt 
0
source