How to do regex-replace in a file using Ansible

ansible

Based on this example:

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

from this documentation, it was tried to do a regex-replace in Ansible.

Ansible version

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

/path/to/file:

helloworld

Ansible snippets:

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

attempt 2

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

Expected outcome:

hello030

Current outcome:

\1030

Questions

  1. Why is the outcome \1030 instead of hello030?
  2. How to solve it?

Best Answer

Why is the outcome \1030 instead of hello030?

The lineinfile module default is backrefs: false. Your regexp='^(hello)world$' matches the entire contents of file. Literal from line='\1030' replaces contents.

How to solve it?

  1. Turn on backrefs with backrefs: true
  2. Use a named group in line:

A backref followed by numbers will not function as expected. You will need a named group instead. e.g. \g<1>

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