Awk

僅在第一個匹配模式之前插入行塊

  • September 8, 2022

server {我需要在 /etc/nginx/nginx.conf 中的第一個匹配字元串之前插入以下行(在變數替換之後)

多變的:

website=www.hello.com

行塊:

server {
# Permanent redirect to www
server_name  ${website:4};
rewrite ^/(.*)$ http://$website/$1 permanent;
}

變數替換後,要插入的行塊應如下所示:

server {
# Permanent redirect to www
server_name  hello.com;
rewrite ^/(.*)$ http://www.hello.com/$1 permanent;
}

我進行的以下嘗試有兩個問題。

問題 1:程式碼在每個(多個)匹配模式之前添加行塊,而不僅僅是第一個。

問題 2:變數的值website沒有被替換www.hello.com

cat myattempt.sh
awk '
/server {/ {
   print "server {"
   print "# Permanent redirect to www"
   print "server_name  ${website:4};"
   print "rewrite ^/(.*)$ http://$website/$1 permanent;"
   print "}"
}
{ print }
' /etc/nginx/nginx.conf > /etc/nginx/nginx.conf.tmp
mv /etc/nginx/nginx.conf.tmp /etc/nginx/nginx.conf

為了測試我的嘗試創建/etc/nginx/nginx.conf如下

貓 /etc/nginx/nginx.conf

http 
{
#  server   {
}

server  { 
}
}

執行 myattempt.sh

目前輸出:cat /etc/nginx/nginx.conf

http 
{

server {
# Permanent redirect to www
server_name  ${website:4};
rewrite ^/(.*)$ http://$website/$1 permanent;
}

#  server   {
}

server {
# Permanent redirect to www
server_name  ${website:4};
rewrite ^/(.*)$ http://$website/$1 permanent;
}
server  { 
}
}

預期輸出:

貓 /etc/nginx/nginx.conf

http 
{

server {
# Permanent redirect to www
server_name  hello.com;
rewrite ^/(.*)$ http://www.hello.com/$1 permanent;
}

#  server   {
}

server  { 
}
}

你能建議嗎?

這可能是你想要做的:

$ cat tst.sh
#!/usr/bin/env bash

website=www.hello.com

new='
server {
# Permanent redirect to www
server_name  '"${website:4}"';
rewrite ^/(.*)$ http://'"$website"'/$1 permanent;
}
'

awk -v new="$new" '
   /server *\{/ && !f++ {
       print new
   }
   { print }
' "${@:-}"
$ ./tst.sh file
http
{

server {
# Permanent redirect to www
server_name  hello.com;
rewrite ^/(.*)$ http://www.hello.com/$1 permanent;
}

#  server   {
}

server  {
}
}

用於從同名的 shell 變數中-v填充 awk 變數將解釋轉義序列,使其像字元串一樣,並將成為文字製表符和換行符。如果這是一個問題,請改為使用或獲取 shell 變數的值,請參閱how-do-i-use-shell-variables-in-an-awk-scriptnew``\t``\n``ENVIRON[]``ARGV[]

引用自:https://unix.stackexchange.com/questions/716523