使用 Ansible 替换文件中的单词

问题描述 投票:0回答:2

我试图替换文件中的一个字符串。例如:

$PASSWORD="oldpassword"

与:

$PASSWORD="newpassword"

这是应该执行此操作的 Ansible 任务:

- name: change password with lineinfile 
  lineinfile:
    dest: test.txt
    regexp: '^$PASSWORD='
    line: '^$PASSWORD="newpassword"'
    state: present
    backrefs: yes 

不幸的是我找不到它不起作用的原因。我无法用新字符串替换它。

我也尝试过不使用

backrefs
并且添加了字符串而不是替换了字符串。

请指教。 谢谢。

ansible ansible-2.x
2个回答
6
投票

来自正则表达式运算

$:匹配字符串末尾或末尾换行符之前 字符串

所以,用反斜杠转义

$

  - lineinfile:
      dest: /tmp/test.txt
      regexp: '^\$PASSWORD='
      line: '$PASSWORD="newpassword"'
      state: present

此外,您不需要在示例中使用

backrefs
参数,因为您的正则表达式没有反向引用。


0
投票
- lineinfile:
      dest: /tmp/test.txt
      regexp: "^PASSWORD=.+"
      line: "PASSWORD=\"newpassword"\"
  

嗨,这段代码对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.