如何使用Vim根据模式将文本分成多行? [英] How to split text into multiple lines based on a pattern using Vim?

查看:471
本文介绍了如何使用Vim根据模式将文本分成多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有以下文字:

name1 = "John"; age1 = 41;
name2 = "Jane"; age2 = 32;
name3 = "Mike"; age3 = 36;
...

,您想将每一行分成两行,以得到如下结果:

and you want to split each line into two lines to give a result like this:

name1 = "John";
age1 = 41;
name2 = "Jane";
age2 = 32;
name3 = "Mike";
age3 = 36;
...

您将如何自动执行此操作?

How would you automate this operation?

一些注意事项:

  1. 我已经尝试了以下方法:
    (1)在virtual-vode中选择文本,
    (2)执行:'<,'>:norm ^3f r^M ***,
    但是它不能正常工作;它只拆分一半的行,因为在每一行都断开之后,命令的下一个重复应用于下一行的其余部分,而不是下一行!
  2. 这可以使用宏来实现,但我正在寻找更优雅的解决方案.


  1. I already tried the following method:
    (1) Select the text in virtual-vode,
    (2) Execute :'<,'>:norm ^3f r^M ***,
    but it doesn't work correctly; it splits only half of the lines, because after every line is broken, the next repetition of the command applies to the rest of the broken line instead on the next line!
  2. This can be achieved using a macro but I'm looking for more elegant solution.


*** 该序列的说明:

-norm用于在正常模式下执行以下命令
-^用于将光标移动到行首
-3f<space>用于将光标移至行中的第三个空格
-r^M用换行符替换该空间

-norm for executing the following commands in normal-mode
-^ for moving the cursor to the beginning of the line
-3f<space> for moving the cursor to the 3rd space in the line
-r^M for replacing that space with a new-line

推荐答案

要对整个文件进行操作,请使用以下方法:

To operate on the entire file, use this:

:%s/; /;\r/

要仅对所选文本进行 操作,请使用以下命令:

To operate only on the selected text, use this:

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

英语翻译:

"将每次出现的 分号后跟空格 替换为 分号后跟换行符 >."

说明:

%    -    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)

这与在Vi中进行替换一样基本.

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

更多令人讨厌的东西:

在这样的情况下,我实际上在.vimrc文件中映射了以下内容:

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. 搜索;(您可能会或可能不想在其中添加空格...由您决定)
  2. 在普通模式下键入以下命令:SS
  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.

为澄清起见,您将使用以下5次击键:

To clarify, you would use the following 5 keystrokes:

/ ; ENTER S S

这对于快速格式化XML,HTML等非常方便...

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

这篇关于如何使用Vim根据模式将文本分成多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆