在跨越多行的模式之后,如何在文件中插入一行

时间:2017-03-15 19:17:43

标签: linux bash shell unix

我想在第一次使用bash显示此模式后插入一行。我该怎么做呢?我想尝试使用模式匹配location / {*}

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
            # Uncomment to enable naxsi on this location
            # include /etc/nginx/naxsi.rules
    }

我希望它成为

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
            # Uncomment to enable naxsi on this location
            # include /etc/nginx/naxsi.rules
    }
    location /hbnb_static

谢谢,我很感激帮助。

1 个答案:

答案 0 :(得分:0)

我尝试了一个Perl单行程序:

perl -e '$s.=$_ while <>; $s=~s|location / \{.*?\}|$&\n    location /hbnb_static|s; print $s' inputfile

一些解释:

  • inputfile拖入变量$s
  • s正则表达式修饰符使.也匹配换行符
  • .*?很懒,所以当遇到后续的}
  • 时会停止
  • 我假设你在插入的行前面也想要4个空格缩进。
  • 将结果打印到stdout

要将其转换为在命令行上读取STDIN或文件的bash脚本,并将修改后的文本打印到stdout:

#!/bin/bash
perl -e '$s.=$_ while <>; $s=~s|location / \{.*?\}|$&\n    location /hbnb_static|s; print $s' $1