How to do regex-replace in a file using Ansible?

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

Tags:

Ansible