如何使用Ansible在文件中replace正则expression式?

基于这个例子:

- lineinfile: dest=/opt/jboss-as/bin/standalone.conf regexp='^(.*)Xms(\d+)m(.*)$' line='\1Xms${xms}m\3' backrefs=yes 

从这个文档中 ,它试图在Ansible中进行正则expression式replace。

Ansible版本

 user@server:/home$ ansible --version ansible 2.1.1.0 

/path/到/文件:

 helloworld 

Ansible片段:

 - lineinfile: dest: /path/to/file regexp='^(hello)world$' line='\1030' 

尝试2

 - lineinfile: dest: /path/to/file regexp='^(hello)world$' line="\1030" 

预期结果:

 hello030 

目前的结果:

 \1030 

问题

  1. 为什么结果是\1030而不是hello030
  2. 如何解决?

为什么结果是1030而不是hello030?

lineinfile模块默认是backrefs: false 。 您的regexp='^(hello)world$'匹配文件的全部内容。 从line='\1030'文字replace内容。

如何解决?

  1. 使用backrefs: true打开backrefs: true
  2. line:使用命名组line:

一个backref后跟数字将无法按预期方式运行。 您将需要一个命名的组。 例如\g<1>

 - name: Replace the world lineinfile: dest: file regexp: '^(hello)world$' line: '\g<1>030' backrefs: true 

我想这是因为它匹配整个\ 1030(作为第1030个backref)。 也许先尝试\ 1 030,如果是这样的话,你会看到。