The ex command <code>g</code> is very useful for acting on lines that match a pattern. You can use it with the <code>d</code> command, to delete all lines that contain a particular pattern, or all lines that do not contain a pattern.

The ex command <code>g</code> is very useful for acting on lines that match a pattern. You can use it with the <code>d</code> 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 firstcommandis optional; it shows the lines that the second command will delete):

+

For example, to delete all lines containing "profile" (remove the <code>/d</code>toshow the lines that the command will delete):

<pre>

<pre>

−

:g/profile

:g/profile/d

:g/profile/d

</pre>

</pre>

Line 61:

Line 60:

</pre>

</pre>

But again I think the faster way to do that is to use :[range]d several times.

But again I think the faster way to do that is to use :[range]d several times.

+

+

How would you instead of deleting, replace matched lines with a ''single'' newline between remaining lines?

Latest revision as of 14:24, August 5, 2014

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" (remove the /d to show the lines that the command will delete):

:g/profile/d

More complex patterns can be used, such as deleting all lines that are empty or that contain only whitespace:

:g/^\s*$/d

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:

:g!/^\s*"/d

Note that g! is equivalent to v, so you could also do the above with:

:v/^\s*"/d

The next example shows use of \| ("or") to delete all lines except those that contain "error" or "warn" or "fail" (:help pattern):

If you simply put delete inside the if statement all the lines will be deleted. Much faster solution is to record a macro "ddj" and play it over the file.
You could delete lines from several different ranges: