簡體   English   中英

Vim:將選擇的每一行的第一個單詞替換為列表中的數字

[英]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]
  • 如果每行只有1個替換,則從上面執行: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 + VCtrl + A

您可以使用以下功能:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM