【问题标题】:add file contents between placeholders in different file在不同文件的占位符之间添加文件内容
【发布时间】:2013-08-05 21:00:37
【问题描述】:

我需要在另一个文本文件的某些占位符之间添加文本文件的内容。 (具体来说,我正在尝试绕过 nginx include limitation inside upstream blocks。)

我的主要nginx配置文件/etc/nginx/nginx.conf是这样的:

## START UPSTREAM

## END UPSTREAM

http {
...
}

我的服务器上游文件/etc/nginx/upstream.conf 如下所示:

upstream wordpress {
  server    10.0.0.1;
  server    10.0.0.2;
  ...
}

我想将/etc/nginx/upstream.conf 的内容复制到## START UPSTREAM## END UPSTREAM 块之间。期望的结果:

## START UPSTREAM
upstream wordpress {
  server    10.0.0.1;
  server    10.0.0.2;
  ...
}
## END UPSTREAM

http {
...
}

到目前为止,我已经尝试使用sed(在otherStackOverflowsolutions的帮助下):

sed -i '/## START UPSTREAM/,/## END UPSTREAM/ r /etc/nginx/upstream.conf' /etc/nginx/nginx.conf

但是,上面的代码不起作用——它只是默默地失败了。如何修改 sed 以正确替换占位符之间的所有文本?

提前致谢!

【问题讨论】:

    标签: bash sed


    【解决方案1】:

    这可能对你有用(GNU sed):

    sed -i -e '/## START UPSTREAM/,/## END UPSTREAM/{//!d;/## START UPSTREAM/r /etc/nginx/upstream.conf' -e '}' /etc/nginx/nginx.conf
    

    【讨论】:

    • 我得到一个错误:sed: -e expression #1, char 1: unknown command: `-'
    • 啊,谢谢,现在可以使用了。但是,每次我运行命令时,它都会像这样复制块:pastebin.com/Zvv8eb3e。如何确保它也替换所有当前块内容?
    • 我猜这里。但我认为您可能需要将您的 nginx.conf 文件编辑回原始状态,然后应用上述解决方案。可能是因为一次又一次地运行解决方案,该文件现在已损坏。
    【解决方案2】:

    我会使用 Perl 而不是 sed

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    my $config   = '/etc/nginx/nginx.conf';
    my $upstream = '/etc/nginx/upstream.conf';
    
    local $/;
    open FILE, "<$config" or die $!;   my $cnf=<FILE>; close FILE;
    open FILE, "<$upstream" or die $!; my $inc=<FILE>; close FILE;
    
    $cnf =~ s/(## START UPSTREAM)[\s\S]*?(## END UPSTREAM)/$1\n$inc$2/;
    
    open FILE, ">$config" or die $!; print FILE $cnf; close FILE;
    

    【讨论】:

      【解决方案3】:

      这里使用保持空间的解决方案(...可能不是您要找的):

      sed -n '
      /\#\# START UPSTREAM/!{H;}; 
      /\#\# START UPSTREAM/{p;}; 
      ${x;p;}' /etc/nginx/upstream.conf /etc/nginx/nginx.conf
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多