sed正则表达式匹配后跳过行

时间:2015-01-05 01:04:35

标签: regex bash nginx sed elastic-beanstalk

我正在尝试使用sed编辑aws elasticbeanstalk nginx配置文件。我想在默认位置块之后插入一个新的位置块。

要做到这一点,我匹配前一个位置块中的一行,然后我想跳过8行,然后插入文本。

这是我运行sed之前的样子

upstream nodejs {
    server 127.0.0.1:8081;
    keepalive 256;
}

server {
    listen 8080;

    location / {
        proxy_pass  http://nodejs;
        proxy_set_header   Connection "";
        proxy_http_version 1.1;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    }

}

这是我天真地尝试构建实际上不起作用的命令,而只是将新块粘贴在包含proxy_pass http://nodejs;的行下。

sed -i '/nodejs;/a \ location ^~ /blog {}' /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf

如何在我regex中识别的行之后跳过8行。另外,我还要了解另一种确定我想要放置新块的方法的建议。

1 个答案:

答案 0 :(得分:3)

这会查找nodejs;并向下跳八行,然后插入location ^~ /blog {}。您没有显示所需的输出,但根据问题,我推断这是您正在寻找的:

$ sed '/nodejs;/ {n;n;n;n;n;n;n;n;s/^/    location ^~ \/blog {}\n/}' file
upstream nodejs {
    server 127.0.0.1:8081;
    keepalive 256;
}

server {
    listen 8080;

    location / {
        proxy_pass  http://nodejs;
        proxy_set_header   Connection "";
        proxy_http_version 1.1;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location ^~ /blog {}
}

如何运作

sed命令是:

/nodejs;/ {n;n;n;n;n;n;n;n;s/^/ location ^~ \/blog {}\n/}

首先查找包含nodejs;的行,并在找到时执行后面的大括号中的语句。

n打印当前模式空间并读入下一行。我们这样做八次。这具有向下跳八行的效果。

s/^/ location ^~ \/blog {}\n/在第八行进行更改。

相关问题