Delete Lines Matching Specific Pattern in a File using VIM

|
Last Updated:
|
|

This guide will take you through how to delete lines matching specific pattern in a file using VIM. Linux system admins work with files day in day out. At some point, you may want just to delete lines matching a specific pattern or a string in a file. There are quite a number of tools out there that you can use to achieve the same. However, this we are going to focus on using VIM.

Delete Lines Matching Specific Pattern in a File Using VIM

In order to delete lines matching a pattern in a file using vim editor, you can use ex command, g in combination with d command.

To remove lines that contains the string amos, in vim command mode, type the command below and press Enter.

:g/amos/d

Similarly, to delete multiple lines with multiple patterns, you can use;

:g/amos\|mibey/d

This will delete all lines containing the specified keywords.

To delete empty lines or lines with white spaces (s);

:g/^\s*$/d
or
:g/^$/d

To delete all the lines that do not contain a specific pattern. For example to delete all the lines that do not contain the string amos

:g!/amos/d

To delete all the lines that do not contain more than one string for example that do not contain the strings amos or mibey.

:g!/amos\|mibey/d

You can also use v instead of g!.

:v/amos\|mibey/d

That is all about how to delete lines matching specific pattern in a file using VIM. If you have other suggestions, be sure to drop a comment. Thank you.

Are you looking at deleting lines matching specific patterns or keyword in a file using SED? See our article by following the link below;

Delete Lines Matching a Specific Pattern in a File using SED

SUPPORT US VIA A VIRTUAL CUP OF COFFEE

We're passionate about sharing our knowledge and experiences with you through our blog. If you appreciate our efforts, consider buying us a virtual coffee. Your support keeps us motivated and enables us to continually improve, ensuring that we can provide you with the best content possible. Thank you for being a coffee-fueled champion of our work!

Photo of author
koromicha
I am the Co-founder of Kifarunix.com, Linux and the whole FOSS enthusiast, Linux System Admin and a Blue Teamer who loves to share technological tips and hacks with others as a way of sharing knowledge as: "In vain have you acquired knowledge if you have not imparted it to others".

2 thoughts on “Delete Lines Matching Specific Pattern in a File using VIM”

Leave a Comment