Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use gvim to add a carriage return (aka ENTER) to a pattern?

Tags:

regex

vim

What's the vi/gvim syntax to replace a pattern with a pattern that includes <ENTER>? I know this is possible but never felt like diving too deep in the documentation to know how to do it.

Something like this:

 :s/\(word\)/\1<ENTER>/

But correctly :)

Thanks

like image 376
OscarRyz Avatar asked Apr 02 '09 18:04

OscarRyz


People also ask

How do I insert a carriage return in Vim?

Ctrl - V tells vi that the next character typed should be inserted literally and ctrl - m is the keystroke for a carriage return.

How do I show a carriage return in Unix?

Use the -b switch for binary mode. For example , vi -b filename or vim -b filename -- . It will then show CR characters ( x0D ), which are not normally used in Unix style files, as the characters ^M . Save this answer.

How do I create a new line character in Vim?

Use \r instead of \n . Substituting by \n inserts a null character into the text. To get a newline, use \r . When searching for a newline, you'd still use \n , however.

How to replace space with new line Vim?

Use \s instead of a space if you want to include tabs, too. And \s\+ if you want it to replace consecutive spaces and/or tabs with one newline.


2 Answers

Use the "escape" encoding:

:s/\(word\)/\1\r/

See the Vim documentation for pattern whitespace escapes.

like image 76
dwc Avatar answered Oct 21 '22 22:10

dwc


:s/\(word\)/\1\r/

Alternatively, use Ctrl+V or Ctrl+Q to quote (escape) the Enter key:

:s/\(word\)\1^QENTER/

Where ^Q is Ctrl+Q and ENTER is the Enter key.

Clarification: Depending on your installation, either ^Q or ^V should work. The quoting character differs on some platforms.

(This has the helpful side-effect of inserting the appropriate end-of-line character for whichever platform you're using, eliminating the CR vs. LF vs. CRLF problem.)

like image 28
Adam Liss Avatar answered Oct 21 '22 22:10

Adam Liss