vim

Search and replace new lines in Vim

Solution

 When using the search and replace feature in Vim (:%s/search/replace/), you must use \n to search for new line characters and \r to replace them with new line characters.

Example of replacing new line characters with commas:

:%s/\n/,/g

Example of replacing commas with new line characters:

:%s/,/\r/g

Reference groups in search and replace in Vim

Solution

Use \x where x is the number of the group and backspace group parentheses.

Let’s say you want to add dashes around digits in a text file, from “today is 20 May 2022” to “today is -2–0- May -2–0–2–2-”. You can do it like this:

:%s/\(\d\)/-\1-/g