Question: I have a file called ***myfile.php*** in which I have a line : 

```
$host:"" //this is where Ansible will add host IP address

```

I want this line to looks like :

```
$host:"192.168.0.12"

```

So I have two questions here: 

1. How to do so with Ansible playbook, like how to define a regular expression that says grep the line which starts with `$host` and ends with `//this is where Ansible will add host IP address` then put between `""` this IP address `162.168.168.0.12`. I want to **modify** this line and not to replace it although I know it will lead the same result.
2. how to make Ansible grep this IP address automatically from the host and avoid typing it manually in the playbook.

Your answers will be very helpful, Thank you.

Answer: 
Use the `replace` module.

```
cat testfile 

$host:"" //this is where Ansible will add host IP address

```

Running playbook:

```
ansible-playbook test.yaml
    ---
    - hosts: localhost
      gather_facts: no
      tasks:
        - replace:
            path: testfile
            replace: "$host:\"{{item}} "
            regexp: '\$host:\"'
          with_items:
            - 192.168.0.12
            - 192.168.0.13

```

This will make it write after your `$host: "` and will stay between `""`

```
cat testfile 

$host:"192.168.0.13 192.168.0.12 " //this is where Ansible will add host IP address

```

> 
> Reference:
>  <http://docs.ansible.com/ansible/latest/modules/replace_module.html#replace-module>
> 
> 
>
This is the solution : 

```
 - name : modify myfile.php
      lineinfile:
        path: /home/myfile.php
        regexp: '^(.*\$host=)(.*this where ansible will add IP host)'
        line: '\1 192.168.0.2\2'
        backrefs: yes

```

The regular expression will split the line into two groups (parts), group 1 : `$host="` and group 2 : `" //this is where Ansible will add host IP address`

and when we define **line: '\1 192.168.0.2\2'** , Ansible will append 192.168.0.2 between the two groups (defined by \1 and \2).

Check <https://regex101.com> to play with regular expressions and see how it works.

Still have a little problem with that white space between `\1` and `192.168.0.2`. If it is removed Ansible will look for `\1192` group which doesn't actually exist, therefore it throws an error while executing the playbook.
An alternative solution for that is to remove `""` from the file and put them in the playbook : line: '\1"192.168.0.2"\2' 
The line now looks like this : 

```
$host:"192.168.0.2" //this is where Ansible will add host IP address

```

Yeah ! I know, comment still there but it's okay for me.

I hope it helps.