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

标签 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

谢谢,非常感谢您的帮助。

最佳答案

我尝试了 Perl 单行代码:

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

一些解释:

  • inputfile 插入变量 $s
  • s 正则表达式修饰符使 . 也匹配换行符
  • .*? 是惰性的,所以遇到后续的}
  • 就停止
  • 我假设您也想在插入的行前面缩进 4 个空格。
  • 将结果打印到标准输出

将其制作成一个 bash 脚本,该脚本在命令行上读取 STDIN 或文件,并将修改后的文本打印到标准输出:

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

关于linux - 在跨越多行的模式之后如何在文件中插入一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42818809/

相关文章:

php - 在 Ubuntu Trusty 上处理 php5.4

bash - 制作一个带有参数的 Bash 别名?

shell - 在 awk 中使用 OFMT

linux - 如何将 git 从一台服务器备份到另一台服务器

linux - Ansible 剧本创建输出到日志文件

cpanel cronjob中的Mysql计划事件

python - 将两行中的值附加到 key 对中

bash - Uniq 许多文件到位

linux - 文件重命名问题

linux - 守护进程拒绝执行不安全的程序