hobbes3
hobbes3

Reputation: 30218

In Vim how do I split a long string into multiple lines by a character?

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!

Upvotes: 36

Views: 30099

Answers (4)

Wong Jia Hau
Wong Jia Hau

Reputation: 3069

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

Upvotes: 2

Pengfei.X
Pengfei.X

Reputation: 681

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

Upvotes: -3

jahroy
jahroy

Reputation: 22692

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

Upvotes: 80

Andrew Marshall
Andrew Marshall

Reputation: 96914

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

:s/|/|\r/g

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

Upvotes: 21

Related Questions