Replace all newlines between "two lines with certain patterns" with a comma in vim

590 views Asked by At

If I have to replace newlines with comma for all lines between Pattern 1 and Pattern 2, how do I do it?

From:

Pattern 1  
abcd
edfgads asd
adsad
...
Pattern 2

to:

Pattern 1, abcd, edfgads asd, adsad, ..., Pattern 2
5

There are 5 answers

0
Tomalak On BEST ANSWER

How about

:%s/Pattern 1\_.\{-}Pattern 2/\=join(split(submatch(0), "\n"), ", ")/g

Search

Pattern 1     # obvious
\_.           # any character including newline
\{-}          # repeat non-greedily (vim's way of writing *?)
Pattern 2     # obvious

The replace part should be clear without an explanation.

0
lcd047 On

Use Pattern 1 and Pattern 2 as addresses, see :help cmdline-ranges:

:/^Pattern 1/,/^Pattern 2/-1 s/\n/, /
0
TessellatingHeckler On
:g/Pattern1/norm V/Pattern2^MgJ
  • :g/ on lines matching Pattern1, run the normal mode keystrokes:

    • visual select as far as... /search for Pattern2
    • gJ Join selected lines, without adding spaces

    NB. Type the ^M with Ctrl-V <Enter>, or Ctrl-Q <Enter>

2
streetturtle On

For vim it would be

:%s/\n/, /g

You search for a newline character: \n and replace it with comma and space: , which is done globally g, these options are split by / character.

More info about replace in vim you can find here

3
Anurag Peshne On

You can put line number while substituting.

:{pattern1LineNo},{pattern2LineNo}s/\n/, /g