3

What character do I use for the newline on Vim search and replace commands?

I'm trying to make this:

1, 
2, 
3, 
4, 
5 

to this: 1, 2, 3, 4 ,5

So i thought of writing something like: :%s/$/\b/g

But it didn't work even if I set: :set magic. How can I achieve that?

David Cain
  • 16,484
  • 14
  • 65
  • 75
user1410363
  • 189
  • 1
  • 3
  • 12

5 Answers5

9

Newlines are represented by \n.

So, with such a simple example, you can replace every newline with:

%s/\n//g

You can replace each comma, followed by optional whitespace until the end of a line with a space, like so:

:%s/,\s*$\n/, /g

Of course, the J operator will most likely suit your needs just fine as well (try Jip within the block you wish to concatenate. Or to automatically line wrap per your textwidth setting: gqip.

David Cain
  • 16,484
  • 14
  • 65
  • 75
3

you don't need :s this will do the job:

gg5J
Kent
  • 189,393
  • 32
  • 233
  • 301
1

Use this search and replace command:

:%s/,\n/, /g

The \n character matches the newline in the search string.

As a sidenote, if you want to insert a newline character in the replace string make sure to use \r instead.

Tuxdude
  • 47,485
  • 15
  • 109
  • 110
1

Alternative would be the :join command.

:%j

For more information see

:h :j
Peter Rincker
  • 43,539
  • 9
  • 74
  • 101
0

You can use visual mode to select the lines that you want to join

ggvGJ

gg takes you to the top of the document. v puts you in visual mode G takes you to the bottom of the document (thereby highlighting all rows) J joins all rows in the selected range.

Barton Chittenden
  • 4,238
  • 2
  • 27
  • 46