4

I am trying to use sed to uncomment a block of text in this config file. The code I came up with uncomments 7 lines starting from and including the pattern match on the first match but I need it to only work on the second match and skip the first match.

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

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#    proxy_pass   http://127.0.0.1;
#}

# pass the PHP scripts 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 scripts to FastCGI server listening on 127.0.0.1:9000
#

>

Mason Mason
  • 67
  • 1
  • 1
  • 4

3 Answers3

3

This might work for you (GNU sed):

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

Use the hold space (HS) to store a flag and only act on the address range if the flag has been set.

potong
  • 55,640
  • 6
  • 51
  • 83
1

I would say, using shell script to change your codes is risky. many special case could make it fail.

I would call it "text transformation" instead. it will remove the leading # from #location ~ \.php$ { line to 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 scripts to Apache listening on 127.0.0.1:80
#
 location ~ \.php$ {
     proxy_pass   http://127.0.0.1;
 }

# pass the PHP scripts 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 scripts to FastCGI server listening on 127.0.0.1:9000
#

I hope the output above is what you need.

Kent
  • 189,393
  • 32
  • 233
  • 301
  • Thanks so much but I need the first match to be ignored and I dont have any experience with awk to play around and modifiy it – Mason Mason Feb 23 '13 at 01:14
0

With (this is more suitable & 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
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • thanks mate, I couldn't get this to work as is, I must have done something wrong. I appreciate your your help though. – Mason Mason Feb 23 '13 at 05:07