Vim: Delete all lines matching a pattern
Learn how to delete all lines matching specific patterns, covering multiple patterns, ranges, case-(in)sensitivity, and other advanced techniques with examples.
\r
is used to insert a newline, while \n
represents a null byte (0x00
or ^@
). Understanding these differences is important.If you ignore these differences you may end up inserting characters like ^M
(Ctrl-M
) or ^@
(ASCII null character 0x00
), instead of the newline.
Below I have put together some examples that explain how searching for newlines and/or replacing with newlines works in Vim.
If you want to remove newlines and, e.g. join lines together, you can search for \n
and replace it with a space or nothing. For example, to join lines into a single paragraph by removing newlines, use:
:%s/\n/ /g
This command searches for newlines (\n
) and replaces them with a space. If you want to remove the newlines without adding spaces, use:
:%s/\n//g
If you need to replace a single newline with two newlines to add extra spacing between lines, you can use:
:%s/\n/\r\r/g
Since \r
is used for newlines in the replacement section, this command effectively doubles the line spacing by adding an extra newline for each occurrence.
foo
and replacing with a newline #To search for the word foo
and replace it with a newline, use:
:%s/foo/\r/g
This replaces every occurrence of foo
with a newline, effectively splitting the text at those points.
Sources and recommended, further resources on the topic:
Search and replace with newline in Vim by Jonas Jared Jacek is licensed under CC BY-SA 4.0.
This license requires that reusers give credit to the creator. It allows reusers to distribute, remix, adapt, and build upon the material in any medium or format, for noncommercial purposes only. To give credit, provide a link back to the original source, the author, and the license e.g. like this:
<p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://www.ditig.com/search-and-replace-with-newline-in-vim">Search and replace with newline in Vim</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://www.j15k.com/">Jonas Jared Jacek</a> is licensed under <a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank" rel="license noopener noreferrer">CC BY-SA 4.0</a>.</p>
For more information see the Ditig legal page.
“Content precedes design. Design in the absence of content is not design, it's decoration.”