33

I have this long regex string

(\.#.+|__init__\.py.*|\.wav|\.mp3|\.mo|\.DS_Store|\.\.svn|\.png|\.PNG|\.jpe?g|\.gif|\.elc|\.rbc|\.pyc|\.swp|\.psd|\.ai|\.pdf|\.mov|\.aep|\.dmg|\.zip|\.gz|\.so|\.shx|\.shp|\.wmf|\.JPG|\.jpg.mno|\.bmp|\.ico|\.exe|\.avi|\.docx?|\.xlsx?|\.pptx?|\.upart)$

and I would like to split it by | and have each component on a new line.

So something like this in the final form

(\.#.+|
__init__\.py.*|
\.wav|
\.mp3|
\.mo|
\.DS_Store|
... etc

I know I can probably do this as a macro, but I figured someone smarter can find a faster/easier way.

Any tips and helps are appreciated. Thanks!

hobbes3
  • 28,078
  • 24
  • 87
  • 116

4 Answers4

76

Give this a try:

:s/|/|\r/g

The above will work on the current line.

To perform the substitution on the entire file, add a % before the s:

:%s/|/|\r/g

Breakdown:

:    - enter command-line mode
%    - operate on entire file
s    - substitute
/    - separator used for substitute commands (doesn't have to be a /)
|    - the pattern you want to replace
/    - another separator (has to be the same as the first one)
|\r  - what we want to replace the substitution pattern with
/    - another separator
g    - perform the substitution multiple times per line
jahroy
  • 22,322
  • 9
  • 59
  • 108
20

Replace each instance of | with itself and a newline (\r):

:s/|/|\r/g

(ensure your cursor is on the line in question before executing)

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
  • 6
    Nothing to do with the original question or the answer, but Why is it `\r` instead of `\n`? – Apalala Jun 01 '13 at 13:00
  • 4
    @Aperçu I haven't researched why, but in VIM you must use ``\r``as the replacement character, and it will do the right thing for the underlying OS. If you use ``\n`` as the replacement, the result won't be what one would expect. – Apalala Sep 15 '15 at 11:48
  • @Apalala It was an answer to your question, not a question ;) – Preview Sep 15 '15 at 12:13
  • 1
    @Apalala See [Why is `\r` a newline for Vim?](https://stackoverflow.com/q/71417/211563) – Andrew Marshall Sep 15 '15 at 12:41
  • @Aperçu Nice. Your 8.5k allow you to edit the answer, I think ;-) – Apalala Sep 15 '15 at 16:24
  • @Apalala No it's a comment I can't, but sorry for the misunderstanding :) I think Andrew didn't saw my comment as well haha – Preview Sep 15 '15 at 16:26
0

If you want to split a line by comma, try pressing this sequence (note: if you see <C-v> it means Ctrl-v, if you see <Enter> it means Enter); all other characters should be treated literally:

:s/,/<C-v><Enter>/g

<C-v> allows you to input control characters (or invisible characters) such as Esc, Enter, Tab, etc.

Type :help ins-special-keys for more info.

Demo: https://asciinema.org/a/567645

Wong Jia Hau
  • 2,639
  • 2
  • 18
  • 30
-3

actually you dont have to add |before the patter, try this s/,/,\r/g it will replace comma with comma following a line break.

Pengfei.X
  • 631
  • 6
  • 9