Let’s see the various ways you can delete a line in the vim editor. Delete a single line in vi editor. The deletion of a single line is probably the easiest. The command to perform the deletion is dd, that is pressing the letter ‘d’ in quick succession twice. It is just like double clicking. Go to the line that you want to delete in the editor. You can use this as a filter within vim, too (this will replace all the lines in the file; you could also use (for example) 2,9 instead of% to process lines 2-9, or select the lines you want with V)::%!cut -f1,3- -f1,3-means 'print field one, followed by field three and all fields until the end of the row'.
The ex command
g
is very useful for acting on lines that match a pattern. You can use it with the d
command, to delete all lines that contain a particular pattern, or all lines that do not contain a pattern.For example, to delete all lines containing 'profile' (the first command is optional; it shows the lines that the second command will delete):
More complex patterns can be used, such as deleting all lines that are empty or that contain only whitespace:
To delete all lines that do 'not' contain a pattern, use
g!
, like this command to delete all lines that are not comment lines in a Vim script:Note that
g!
is equivalent to v
, so you could also do the above with:The next example shows use of
|
('or') to delete all lines 'except' those that contain 'error
' or 'warn
' or 'fail
' ({{help|pattern}}):