# Remove a line from file and surrounding

**URL:** <https://forum.ansible.com/t/remove-a-line-from-file-and-surrounding/36734>\
**Category:** Ansible Project\
**Created:** [June 14, 2022, 12:30pm UTC](https://forum.ansible.com/t/remove-a-line-from-file-and-surrounding/36734 "2022-06-14T12:30:01Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Laci](https://avatars.discourse-cdn.com/v4/letter/l/c67d28/32.png) [@Laci](https://forum.ansible.com/u/Laci)\
**Post date:** [June 14, 2022, 12:30pm UTC](https://forum.ansible.com/t/remove-a-line-from-file-and-surrounding/36734/1 "2022-06-14T12:30:01Z")

</div>

I’m working on a playbook which would remove lines from a file containing specific hostname.  
I want to use Ansible to remove the hostname AND surrounding lines. Here is an example of a block that I need to remove:

FileSet {  
Name = “vcenter-hostname05”  
Include {  
Options {  
signature = SHA1  
compression=GZIP  
noatime=yes  
}  
Plugin = “vsphere: server=vsphere-vcenter [host=hostname05.domain.com](http://host=hostname05.domain.com) abort\_on\_error”  
}  
}

Does anyone have a suggestion how would I match the lines when all I have is _hostname05_?

---

<div class="post-metadata">

**Author:** ![Laci](https://avatars.discourse-cdn.com/v4/letter/l/c67d28/32.png) [@Laci](https://forum.ansible.com/u/Laci)\
**Post date:** [June 14, 2022, 2:59pm UTC](https://forum.ansible.com/t/remove-a-line-from-file-and-surrounding/36734/2 "2022-06-14T14:59:38Z")

</div>

So far my best option is to run a command which invokes sed

---

<div class="post-metadata">

**Author:** ![Jeff\_S](https://avatars.discourse-cdn.com/v4/letter/j/d6d6ee/32.png) [@Jeff\_S](https://forum.ansible.com/u/Jeff_S)\
**Post date:** [June 15, 2022, 11:37am UTC](https://forum.ansible.com/t/remove-a-line-from-file-and-surrounding/36734/3 "2022-06-15T11:37:00Z")

</div>

You can use those **modules, replace & lineinfile** , to search for a pattern and replace it with something.  
[ansible.builtin.replace module – Replace all instances of a particular string in a file using a back-referenced regular expression — Ansible Documentation](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/replace_module.html)  
[ansible.builtin.lineinfile module – Manage lines in text files — Ansible Documentation](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/lineinfile_module.html)  
or use the **shell module** to work with sed!

---

<div class="post-metadata">

**Author:** ![Laci](https://avatars.discourse-cdn.com/v4/letter/l/c67d28/32.png) [@Laci](https://forum.ansible.com/u/Laci)\
**Post date:** [June 21, 2022, 9:18am UTC](https://forum.ansible.com/t/remove-a-line-from-file-and-surrounding/36734/4 "2022-06-21T09:18:56Z")

</div>

Thank you Jeff!  
I ended up using a shell script with sed.
