[英]Vim: Replace first word on each line of selection with number in list
我有一個很大的文件,其中包含一個帶有混雜數字的選擇。 它應該是1、2、3,...的序列,但有幾行搞砸了。 我想改變像
富
酒吧
1個foobar
12345 foobar
6546458 foobar
4個foobar
至
富
酒吧
1個foobar
2 foobar
3 foobar
4個foobar
我知道我可以使用3,$
類的東西來選擇我關心的行,並put = range(1,1000)
來創建以所需數字開頭的新行,但是我想將這些數字放在當前有數據的行上,而不是新行。 混雜的數字長幾個字符,但總是一個字。 謝謝。
請執行下列操作:
:let i=1
:g/^\d\+/s//\=i/|let i=i+1
設置一些變量( let i=1
)用作我們的計數器。 在以數字( :g/^\\d\\+/
)開頭的每一行中,我們執行替換( :s//\\=i/
),以用我們的計數器( \\=i
)替換模式,然后增加我們的計數器( let i=i+1
)。
:g
呢? 為什么不只是:s
? 您可以使用替換命令來完成此操作,但是sub-replace-expression \\=
需要一個表達式來求值(請參見:h sub-replace-expression
)。 因為let i = i + 1
是一條語句,所以它將無用。
有幾種方法可以解決此問題:
map(arr, 'v:val+1')[0]
:g
技巧 使用就地數組修改的完整示例:
:let i=[1]
:%s/^\d\+/\=map(i,'v:val+1')[0]
就個人而言,我將使用您能記住的任何方法。
:h :s
:h sub-replace-expression
:h :g
:h :let
:h expr
:h map(
:h v:val
/^\d\+\s -- Searches for the first occurrence
ciw0<Esc> -- Replaces the word under cursor with "0"
yiw -- Copies it
:g//norm viwp^Ayiw
-- For each line that matches the last search pattern,
-- Replace the current word with copied text,
-- Increment it,
-- Copy the new value.
( <Esc>
只是Esc 。 ^A
輸入為Ctrl + V , Ctrl + A )
ciw
更改內部單詞。 ( :help c
) :g
全局搜索。 ( :help :g
) viw
選擇內部單詞 ( :help v
) p
粘貼(替換選擇) ( :help v_p
) ^A
遞增。 ( :help CTRL-A
) yiw
-Yank內部單詞。 ( :help y
) 您可以使用以下功能:
function Replace()
let n = 1
for i in range(0, line('$'))
if match(getline(i), '\v^\d+\s') > -1
execute i . 's/\v^\d+/\=n/'
let n = n + 1
endif
endfor
endfunction
它遍歷整個文件,檢查每行是否以數字開頭,后跟空格字符,並用隨每次更改而增加的計數器進行替換。
像這樣稱呼它:
:call Replace()
在您的示例中得出:
foo
bar
1 foobar
2 foobar
3 foobar
4 foobar
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.