问题描述
我经常在列中有文本,需要替换一些内容而不破坏同一行上的类似内容......一个简单的例子如下:
假设我用 vim 可视块模式将文本高亮显示为灰色,并希望将 80
替换为 81
;但是,我只希望在突出显示的视觉块中进行替换.
我已经试过了 : s/80/81/g
;然而,它替换了视觉块内部和外部的文本.(根据 Randy 的反馈,这是因为 : s
是一个逐行命令).
我知道我可以在这个特定实例中使用逐行视觉块替换( : s/80\.1/81.1/g
);但是,我正在尝试为在非逐行视觉块中无法轻松替换的问题找到通用解决方案(这不是视觉块模式应该帮助解决的问题吗?).像 : s/80/81/gc
这样需要确认的答案不是我要找的.p>
为了清楚起见,我将重申这个问题:如何使用 vim 的可视块模式突出显示将 80
替换为 81
?
您需要将 \%V
添加到您的模式中.来自 :help \%V
:
在可视区域内匹配.当可视模式已经在 gv 将重新选择的区域中停止匹配.这是一个/zero-width 匹配.确保整个图案是在可视区域内,将其放在模式的开始和结束处.
OP EDIT:明确的解决方案是使用 : s/\%V8\%V0/81/g
I often have text in columns and need to replace some things without clobbering similar stuff on the same line... a simple example follows:
Suppose I have highlighted the text in grey with vim visual block mode, and want to replace 80
with 81
; however, I only want replacements within the highlighted visual block.
I have already tried : s/80/81/g
; however, that replaces text inside and outside the visual block. (based on Randy's feedback, it's because : s
is a line-wise command).
I know I could use a line-wise visual block replace in this particular instance ( : s/80\.1/81.1/g
); however, I'm trying to find a general solution for the problem of having no easy means to replace within a non line-wise visual block (isn't this the kind problem that visual block mode is supposed to help solve?). Answers requiring confirmation like : s/80/81/gc
, are not what I am looking for.
I will restate the question for clarity: How can I replace 80
with 81
by using vim's visual block mode highlight?
You need to add \%V
to your pattern. From :help \%V
:
Match inside the Visual area. When Visual mode has already been
stopped match in the area that gv would reselect.
This is a /zero-width match. To make sure the whole pattern is
inside the Visual area put it at the start and end of the pattern.
OP EDIT: the explicit solution is to to use : s/\%V8\%V0/81/g
这篇关于vim 搜索和替换仅限于视觉块模式下的突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!