代码之家  ›  专栏  ›  技术社区  ›  DenCowboy

无法使替换工作可靠

  •  2
  • DenCowboy  · 技术社区  · 6 年前

    我试图替换这些行:

    ## Allows people in group wheel to run all commands
    %wheel  ALL=(ALL)       ALL
    
    ## Same thing without a password
    # %wheel        ALL=(ALL)       NOPASSWD: ALL
    

    签署人:

    ## Allows people in group wheel to run all commands
    # %wheel  ALL=(ALL)       ALL
    
    ## Same thing without a password
    %wheel        ALL=(ALL)       NOPASSWD: ALL
    

    我的剧本是这样的:

      - replace:
          path: /etc/sudoers
          regexp: '^%wheel\s\sALL=\(ALL\)\s\s\s\s\s\s\sALL$'
          replace: '^#\s%wheel\s\sALL=\(ALL\)\s\s\s\s\s\s\sALL$'
        become: yes
    
      - replace:
          path: /etc/sudoers
          regexp: '^#\s%wheel\s\s\s\s\s\s\s\sALL=\(ALL\)\s\s\s\s\s\s\sNOPASSWD:\sALL'
          replace: '^%wheel\s\s\s\s\s\s\s\sALL=\(ALL\)\s\s\s\s\s\s\sNOPASSWD:\sALL'
        become: yes
    

    更新但对我不起作用:

      - replace:
          path: /etc/sudoers
          regexp: '^%wheel\s\sALL=\(ALL\)\s\s\s\s\s\s\sALL$'
          replace: '# %wheel  ALL=(ALL)       ALL'
        become: yes
    
      - replace:
          path: /etc/sudoers
          regexp: '^#\s%wheel\s\s\s\s\s\s\s\sALL=\(ALL\)\s\s\s\s\s\s\sNOPASSWD:\sALL'
          replace: '# %wheel    ALL=(ALL)   NOPASSWD: ALL'
        become: yes
    

    我做错什么了?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Wiktor Stribiżew    6 年前

    替换模式是文本字符串,除了反向引用。不要在那里使用regex模式。

    regexp: '^(%wheel\s+ALL=\(ALL\)\s+ALL)$'
    replace: '# \1'
    

    至于第二次更换:

    regexp: '^#\s+(%wheel\s+ALL=\(ALL\)\s+NOPASSWD:\s+ALL)'
    replace: '\1'
    

    这里,那个 (...) 在regex模式中定义捕获组和 \1 在替换中指的是这些被捕获的部分。反向引用允许我们避免重复替换模式中regex模式中使用的文本字符串。 \s+ 匹配一个或多个出现的空白字符。你可以看到 how the second regex works here