如何在 Vim 中高效地交错多组行? [英] How to efficiently interlace multiple groups of lines in Vim?

查看:36
本文介绍了如何在 Vim 中高效地交错多组行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试交错三组文本行.例如,以下文本:

I am trying to interlace three groups of lines of text. For example, the following text:

a
a
a
b
b
b
c
c
c

要转化为:

a
b
c
a
b
c
a
b
c

有没有一种有效的方法来做到这一点?

Is there an efficient way of doing this?

推荐答案

这是一个oneliner"(几乎),但是您必须为每个唯一的减 1 行重做它,在您的示例中为 2 次.也许没有用,但我认为这是一个很好的练习,可以学习更多关于 VIM 中的模式.只要整行是唯一的,它就可以处理所有类型的行(例如 mnomnp 是两个唯一的行).

Here is a "oneliner" (almost), but you have to redo it for every unique line minus 1, in your example 2 times. Perhaps of no use, but I think it was a good exercise to learn more about patterns in VIM. It handles all kind of lines as long as the whole line is unique (e.g. mno and mnp are two unique lines).

首先确保这一点(并且不要/ 映射到任何内容,或该行中的任何其他内容):

First make sure of this (and do not have / mapped to anything, or anything else in the line):

:set nowrapscan

然后映射例如这些(应该是递归的,不是 nnoremap):
应该按字面意思输入.
\v 在模式中的意思是非常神奇",@! 否定前瞻.\2 使用第二个括号中的内容.

Then map e.g. these (should be recursive, not nnoremap):
<C-R> and <CR> should be typed literally.
\v in patterns means "very magic", @! negative look-ahead. \2 use what's found in second parenthesis.

:nmap ,. "xy$/\v^<C-R>x$<CR>:/\v^(<C-R>x)@!(.*)$\n(\2)$/m-<CR>j,.
:nmap ,, gg,.

然后根据需要执行 ,, 多次,在您的示例中为 2 次.一个用于所有 bs,一个用于所有 cs.

Then do ,, as many times as it takes, in your example 2 times. One for all bs and one for all cs.

映射说明.我将使用问题中的示例,就好像它使用此映射运行了一次一样.
跑完一圈:

explanation of the mapping. I will use the example in the question as if it has run one time with this mapping.
After one run:

1. a
2. b
3. a
4. b
5. a
6. b
7. c
8. c
9. c

光标然后在最后一个a(第5行),当输入,,时,它首先回到第一行,然后运行,.,而那个映射就是这样做的:

The cursor is then at the last a (line 5), when typing ,,, it first go back to first line, and then runs mapping for ,., and that mapping is doing this:

"xy$             # yanks current line (line 1) to reg. "x" ("a")  "
/\v^<C-R>x$<CR>  # finds next line matching reg. "x" ("a" at line 3)
:/\v^(<C-R>x)@!(.*)$\n(\2)$/m-<CR>
# finds next line that have a copy under it ("c" in line 7) and moves that line
# to current line (to line 3, if no "-" #after "m" it's pasted after current line)
# Parts in the pattern:
- ^(<C-R>x)@!(.*)$  # matches next line that don't start with what's in reg. "x"
- \n(\2)$           # ...and followed by newline and same line again ("c\nc")
- m-<CR>            # inserts found line at current line (line 3)
j                # down one line (to line 4, where second "a" now is)
,.               # does all again (recursive), this time finding "c" in line 8
...
,.               # gives error since there are no more repeated lines,
                 # and the "looping" breaks.

这篇关于如何在 Vim 中高效地交错多组行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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