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
Hi,
Thanks for this useful article
Deleting multiple lines on a match:
:g/foo/d4
Will delete any line matching foo and the 3 lines below it.