2 回答

TA貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊
由于配置文件可能在這一節(jié)中包含更多內(nèi)容,因此在這里要考慮錯(cuò)誤匹配。特別是,匹配^#\s*}并希望達(dá)到最佳效果可能會(huì)導(dǎo)致注釋掉文件中其他位置完全不相關(guān)的行。
因此,在取消注釋之前,我將收集屬于該部分的所有行。我正在考慮這樣的思路:編寫代碼
/^#\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/
}
進(jìn)入文件uncomment.sed,然后說(shuō),然后運(yùn)行
sed -f uncomment.sed /etc/nginx/sites-available/default
如果結(jié)果令人滿意,請(qǐng)?zhí)砑釉?i選項(xiàng)以進(jìn)行編輯。
該代碼的工作方式如下:
/^#\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/
}

TA貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊
這是一個(gè)gnu-awk帶有自定義選項(xiàng)的替代解決方案RS:
awk -v RS='# location [^{]*{[^}]*}\n' 'RT {
RT = gensub(/(^|\n)[[:blank:]]*#([[:blank:]]*(location|include|fastcgi_pass unix|}))/, "\\1\\2", "g", RT)
RT = gensub(/(php7\.)0/, "\\11", "1", RT)
}
{ORS=RT} 1' file
...
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:/var/run/php/php7.1-fpm.sock;
}
...
添加回答
舉報(bào)