【问题标题】:skip lines after sed regular expression matchsed 正则表达式匹配后跳过行
【发布时间】:2015-01-05 11:03:27
【问题描述】:

我正在尝试使用 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 行。此外,还建议以另一种方式确定我想在哪里放置我的新块。

【问题讨论】:

  • 你能发布新配置的样子吗?
  • 您能否依赖该位置下方} 的缩进。还是最后的}?我认为像awk 这样更高级的东西可能更适合这项任务。

标签: regex bash nginx sed amazon-elastic-beanstalk


【解决方案1】:

这会查找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/ 在第八行进行更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多