【问题标题】:How can search replace multiple lines in a file using sed如何使用 sed 搜索替换文件中的多行
【发布时间】:2016-08-29 23:43:53
【问题描述】:

我在多个文件中都有这个

  vars_files:
    - "{{inventory_dir}}/common/vars/{{type1}}.yml"
    - "{{inventory_dir}}/common/vars/{{type2}}.yml"
    - "{{inventory_dir}}/common/vars/{{type3}}.yml"
    - "{{inventory_dir}}/common/vars/{{type4}}.yml"
  roles:
      bla bla

线条路径可以变化,因此它不是恒定的

现在每次我都必须手动将其更改为多个文件。我正在寻找可以使用 sed 替换的东西。

是否有可能我有 template 文件,其中包含我想要替换的代码

  vars_files:
    - "{{inventory_dir}}/common/vars/{{type22}}.yml"
    - "{{inventory_dir}}/common/vars/{{type22}}.yml"
    - "{{inventory_dir}}/common/vars/{{type32}}.yml"
    - "{{inventory_dir}}/common/vars/{{type42}}.yml"

然后 sed 在文件中查找上述模式并在同一位置替换为上述模板。

我的 sed 知识只是替换多个文件中的某一行代码,例如

find files/ -type f -name "*.yml" -exec sed -i -re 's/\{\{inventory_dir\}\}\/vars\/common\.yml/\{\{inventory_dir\}\}\/common\/vars\/common.yml/g' {} \;

但我不确定如何处理多行。

我正在考虑在 vars_files 和 roles: 之间寻找线,然后用模板替换,但我不确定如何阅读

【问题讨论】:

  • 您搜索过[sed] multiline replace 吗?对此有 99 个 Q/As,但它确实是解决您问题的脆弱解决方案。不建议。您肯定会在此处通过其他一些 Q/As 找到替代方案。祝你好运。

标签: regex linux bash awk sed


【解决方案1】:

sed 用于在单个行上进行简单替换,仅此而已。对于其他任何事情,您都应该使用 awk。这是未经测试的,但将非常接近您的需要:

awk '
NR==FNR { new = new $0 ORS; next }
inVF && ($1 != "-") { inVF=0 }
/vars_files:/ { inVF=1; printf "%s", new }
!inVF
' template file.yml

【讨论】:

    猜你喜欢
    • 2021-02-18
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 2017-11-08
    • 2011-07-13
    • 1970-01-01
    相关资源
    最近更新 更多