首页 > 解决方案 > 注释行与 Ansible 匹配一些模式和后面的 n 个字符串

问题描述

我需要注释匹配模式的行和后面的 n 行(如果行首已经没有注释符号)。当我需要评论任何包含模式“重启”的行时,我会这样做:

    - name: Excluding reboot command from script
      replace:
        path: "{{some_path}}/someshellscript.sh"
        regexp: '(^(?!.*#).*reboot.*)'
        replace: '#\1'

此任务注释行带有“rebo​​ot”和正则表达式将不匹配“#reboot”。但是,如果我需要用 'reboot' 注释行,并且在这行还没有注释的情况下在它之后的两行注释呢?

标签: regexreplaceansiblecomments

解决方案


只要您可以可靠地预测您的行返回将是什么,并且在正则表达式匹配后您需要评论的行数不会有差异,您就可以使用它:

- name: Excluding reboot command from script
  replace:
    path: "{{some_path}}/someshellscript.sh"
    regexp: '(^(?!.*#).*reboot.*\n)(.*\n)(.*)'
    replace: '#\1#\2#\3'

推荐阅读