SED - 将字符串添加到nginx配置块的末尾

问题描述 投票:1回答:1

/etc/nginx/nginx.conf文件默认情况下看起来像这样:

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

我想在http {}块的末尾添加一些内容,例如:

include /etc/nginx/sites-enabled/*.conf;

这样就变成了:

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*.conf;
}

重要的是它不依赖于任何现有内容,它应该以结束括号作为参考点。

我目前有这个代码:

sed -i '/^http {/a\    include \/etc\/nginx\/sites\-enabled\/\*\.conf\;' /etc/nginx/nginx.conf

不幸的是,这是在块的开头插入,而不是结束。

unix sed
1个回答
0
投票

这可能对你有用GNU sed):

sed '/^http {/,/^}/!b;/^}/i\new content' file

使用范围专注于http部分,并在结束}之前插入新内容。

也可以写成:

sed -e '/^http {/,/^}/{/^}/i\new content' -e '}' file
© www.soinside.com 2019 - 2024. All rights reserved.