我想使用sed
取消注释并更改ngnix配置中的几行
这个。。
...
# location ~ \.php$ {
# include snippets/fastcgi-php.conf;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
# # With php-fpm (or other unix sockets):
# fastcgi_pass unix:/run/php/php7.0-fpm.sock;
# }
...
…应该变成这样:
...
location ~ \.php$ {
include snippets/fastcgi-php.conf;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
# # With php-fpm (or other unix sockets):
fastcgi_pass unix:/run/php/php7.1-fpm.sock;
}
...
下面是我用来取消注释前三行的内容:
sudo sed -i 's/#\s*location ~ \\\.php$ {/location ~ \\.php$ {/g' /etc/nginx/sites-available/default
sudo sed -i 's/#\s*include snippets\/fastcgi-php\.conf;/\tinclude snippets\/fastcgi-php.conf;/g' /etc/nginx/sites-available/default
sudo sed -i 's/#\s*fastcgi_pass unix:\/run\/php\/php7\.0-fpm\.sock;/\tfastcgi_pass unix:\/run\/php\/php7\.1-fpm.sock;/g' /etc/nginx/sites-available/default
我设法使这些行工作,但我不知道如何取消注释,而不取消注释文件其余部分的其他人最后的荣誉。你有什么想法吗?
解决方案
多亏温特穆特的回答,我才使事情顺利进行。以下是我的最终解决方案,全部打包在一个命令行中:
sudo sed -i '/^\s*#\s*location ~ \\\.php\$ {/ {
:loop /\n\s*#\s*}/! {
N;
b loop;
};
s@#@@;
s@#\(\s*include snippets/fastcgi-php\.conf;\)@\1@;
s@#\(\s*fastcgi_pass unix:/run/php/php7\.\)[0-9]\+\(-fpm\.sock;\)@\11\2@;
s@\n\(\s*\)#\(\s*}\)@\n\1\2@;
};' /etc/nginx/sites-available/default
最佳答案
由于这一节中的配置文件可能包含更多的thas,所以这里需要考虑错误匹配。特别是,匹配^#\s*}
并希望获得最佳结果可能会取消对文件中其他地方完全不相关的行的注释。
因此,在取消注释之前,我将收集属于所讨论部分的所有行我的思路是:把代码
/^#\s*location ~ \\\.php\$ {/ {
:loop
/\n#\s*}/! {
N
b loop
}
s/^#//
s@#\(\s*include snippets/fastcgi-php\.conf;\)@\1@
s@#\(\s*fastcgi_pass unix:/var/run/php/php7\.\)0\(-fpm\.sock;\)@\11\2@
s/\n#\(\s*}\)/\n\1/
}
输入一个文件,比如
uncomment.sed
,然后运行sed -f uncomment.sed /etc/nginx/sites-available/default
如果结果令您满意,请添加
-i
选项以就地编辑。此代码的工作原理如下:
/^#\s*location ~ \\\.php\$ {/ { # starting with the first line of the section
# (regex taken from the question):
:loop # jump label for looping
/\n#\s*}/! { # Until the last line is in the pattern space
N # fetch the next line from input, append it
b loop # then loop
}
# At this point, we have the whole section in the pattern space.
# Time to remove the comments.
# There's a # at the beginning of the pattern space; remove it. This
# uncomments the first line.
s/^#//
# The middle two are taken from the question, except I'm using @ as
# a separator so I don't have to escape all those slashes and captures
# to avoid repeating myself.
s@#\(\s*include snippets/fastcgi-php\.conf;\)@\1@
s@#\(\s*fastcgi_pass unix:/var/run/php/php7\.\)0\(-fpm\.sock;\)@\11\2@
# Uncomment the last line. Note that we can't use ^ here because that
# refers to the start of the pattern space. However, because of the
# looping construct above, we know there's only one # directly after
# a newline followed by \s*} in it, and that's the comment sign before
# the last line. So remove that, and we're done.
s/\n#\(\s*}\)/\n\1/
}
关于regex - 通过sed取消评论的赞誉,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50269712/