How to split text into multiple lines based on a pattern using Vim?

半世苍凉 提交于 2019-12-04 23:28:00

To operate on the entire file, use this:

:%s/; /;\r/

To operate only on the selected text, use this:

:'<,'>s/; /\r/

English translation:

"Replace every occurrence of semi-colon followed by a space with semi-colon followed by a newline."

Explanation:

%    -    operate on the entire file
s    -    substitute
/    -    symbol that separates search/replace terms
;    -    the character you're searching for (notice I added a space)
;\r  -    the replacement text (semi-colon followed by newline)

That's about as basic as it gets for substitution in Vi.


For more geekiness:

I actually have the following mapped in my .vimrc file for situations like this:

"
" add a newline after each occurrence of the last search term
"
nnoremap SS :%s//&\r/<CR>

This command splits each line of a file at the first occurrence of the last search pattern.

So, for your use-case you would do this:

  1. search for ; (you may or may not want to include a space... up to you)
  2. type the following command in normal mode: SS

Each line of your file will get split at the first ; symbol.

To clarify, you would use the following 5 keystrokes:

/ ; ENTER S S

This is very handy for quickly formatting XML, HTML, etc...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!