Replace multiple lines in a file at different locations

16 views
Skip to first unread message

Suresh Grandhi

unread,
Feb 16, 2017, 1:36:24 AM2/16/17
to Ansible Project
I am looking to replace or delete redundant lines in a file at different line numbers. 

For example, a file has the following content

<value1> <text1>
<value2> <text2>
<value3> <text1>

In this case, I want to remove <value1> <text1>  and replace <value3> <text1> with <valuex> <text1>.
Is there a possibility to do this in Ansible?

Nehal J Wani

unread,
Feb 16, 2017, 8:58:50 AM2/16/17
to ansible...@googlegroups.com

[wani@linux tmp ]$ cat /tmp/a
<value1> <text1>
<value2> <text2>
<value3> <text1>
[wani@linux tmp ]$ cat a.yaml 
- hosts: localhost

  tasks:
    - lineinfile:
        path: /tmp/a
        regexp: "^<value1> <text1>"
        state: absent

    - lineinfile:
        path: /tmp/a
        regexp: "^<value3> <text1>"
        line: "<valuex> <text1>"
[wani@linux tmp ]$ ansible-playbook a.yaml 
 [WARNING]: Host file not found: /etc/ansible/hosts

 [WARNING]: provided hosts list is empty, only localhost is available


PLAY [localhost] ****************************************************************************************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************************************************************************************
ok: [localhost]

TASK [lineinfile] ***************************************************************************************************************************************************************************
changed: [localhost]

TASK [lineinfile] ***************************************************************************************************************************************************************************
changed: [localhost]

PLAY RECAP **********************************************************************************************************************************************************************************
localhost                  : ok=3    changed=2    unreachable=0    failed=0   

[wani@linux tmp ]$ cat /tmp/a
<value2> <text2>
<valuex> <text1>


--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-project+unsubscribe@googlegroups.com.
To post to this group, send email to ansible-project@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/76f8b842-eed8-4785-bd12-227655ecb300%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Nehal J Wani
Reply all
Reply to author
Forward
0 new messages