Vim - 如何增加視覺區塊中的每個數字?

Vim - 如何增加視覺區塊中的每個數字?

我有以下 SQL:

update am.PERMISSIONS set PRM_ORDER = 35 PRM_VISIBLE = b'1' where PRM_ID = 3;
update am.PERMISSIONS set PRM_ORDER = [35] PRM_VISIBLE = b'1' where PRM_ID = 7;
update am.PERMISSIONS set PRM_ORDER = [40] PRM_VISIBLE = b'1' where PRM_ID = 10;
update am.PERMISSIONS set PRM_ORDER = [45] PRM_VISIBLE = b'1' where PRM_ID = 11;
...

我用方括號選擇視覺塊,我想將其中的每個數字增加 5。

答案1

直觀地突出顯示括號中的文字:

Ctr+ V2jl

將每個數字增加 5:

:norm 5Ctr+ V Ctr+A 解釋:

:norm在正常模式下執行整個命令。 +CtrV必需的,否則遊標將跳回行首。 Ctr+A將數字加 1,共進行 5 次。按下冒號後會自動插入可視範圍。

編輯: 正如 Stephane 正確指出的那樣,前面的程式碼會遞增在任何行上找到的第一個數字。這是一個更好的解決方案:

%s/\[\zs\d\+\ze\]/\=(submatch(0)+5)

它將括號內的所有整數加五。和\zs用於\ze從匹配中排除括號並submatch返回匹配的數字。

答案2

您不需要離開視覺模式來增加數字,只需使用g

5 g Ctrl-a

5 ......... 5 times
g ......... globally
Ctrl-a .... increase numbers

事實上我已經學會這個技巧維姆高爾夫挑戰。

答案3

這兩個命令是相同的,並且會增加所有數字之內 視覺選擇(即使是在矩形中!)。

:'<,'>s/\%V\d\+\%V/\=submatch(0)+1/g

:s/\%V\d\+\%V/\=submatch(0)+1/g

斬::s / \%V \d\+ \%V / \=submatch(0)+1 / g

\%V是一個零寬度匹配器,可以匹配目前(或最後一個)選擇範圍內的任何位置。

來自 vim 幫助:

\%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 just before the end of
        the pattern, e.g.:
                /\%Vfoo.*ba\%Vr
        This also works if only "foo bar" was Visually selected. This:
                /\%Vfoo.*bar\%V
        would match "foo bar" if the Visual selection continues after the "r".
        Only works for the current buffer.

不幸的是,這並不那麼聰明,ctrl-a因為它不理解負數。

相關內容