# lineinfile behavior replace line if found, add line if not found?

**URL:** <https://forum.ansible.com/t/lineinfile-behavior-replace-line-if-found-add-line-if-not-found/21184>\
**Category:** Ansible Project\
**Created:** [April 17, 2016, 6:31pm UTC](https://forum.ansible.com/t/lineinfile-behavior-replace-line-if-found-add-line-if-not-found/21184 "2016-04-17T18:31:09Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Bob\_Tanner](https://avatars.discourse-cdn.com/v4/letter/b/49beb7/32.png) [@Bob\_Tanner](https://forum.ansible.com/u/Bob_Tanner)\
**Post date:** [April 17, 2016, 6:31pm UTC](https://forum.ansible.com/t/lineinfile-behavior-replace-line-if-found-add-line-if-not-found/21184/1 "2016-04-17T18:31:09Z")

</div>

Struggling with lineinfile behavior.

The general question: can lineinfile be used to replace a line in a file if it’s found and if it’s not found add the line to the file?

I’ve seen posts saying yes, same saying no, same saying don’t use lineinfile, use a template.

Here’s the recipe I’ve been trying:

lineinfile: \>  
dest=“/tmp/testfile”  
regexp=“(._){{ item.param }}(._)?$”  
line=‘{{ item.param }} {{ item.value }}’  
backrefs=“yes”  
state=“present”  
with\_items:

- { param: ‘testparam’, value: ‘testvalue’ }

The contents of /tmp/testfile

blah blahvalue  
foo foovalue  
ugh ughvalue

I run the task and “testparam testvalue” does not get added to /tmp/testfile

blah blahvalue  
foo foovalue  
ugh ughvalue

testvalue wrongvalue

Run the task again and I get what I think is the right output

blah blahvalue  
foo foovalue  
ugh ughvalue

testvalue testvalue

---

<div class="post-metadata">

**Author:** ![Paulo\_JCranky\_Siquei](https://avatars.discourse-cdn.com/v4/letter/p/ce73a5/32.png) [@Paulo\_JCranky\_Siquei](https://forum.ansible.com/u/Paulo_JCranky_Siquei)\
**Post date:** [April 18, 2016, 7:08am UTC](https://forum.ansible.com/t/lineinfile-behavior-replace-line-if-found-add-line-if-not-found/21184/2 "2016-04-18T07:08:20Z")

</div>

Using “insertafter=EOF” should do the trick.

s,

---

<div class="post-metadata">

**Author:** ![Paul\_Totterman](https://avatars.discourse-cdn.com/v4/letter/p/3ec8ea/32.png) [@Paul\_Totterman](https://forum.ansible.com/u/Paul_Totterman)\
**Post date:** [April 18, 2016, 7:31am UTC](https://forum.ansible.com/t/lineinfile-behavior-replace-line-if-found-add-line-if-not-found/21184/3 "2016-04-18T07:31:21Z")

</div>

Hi Bob,

> The general question: can lineinfile be used to replace a line in a file if it’s found and if it’s not found add the line to the file?

I’ve used it successfully like this, but I didn’t template my regexp.

Cheers,  
Paul
