如何在 Vim/gVim 中找到具有最大列數/字元數的行?

如何在 Vim/gVim 中找到具有最大列數/字元數的行?

我目前在 Windows XP 上使用 gVim,對於我的核心問題我有 2 個後續問題:

找到字元最多的行的最佳方法是什麼?

我目前的方法:我使用正規表示式搜尋:/^\(\p\)\{#number#,}$),並不斷增加整數,#number#直到只得到一個匹配項。就我的文件而言,一行只有 81K 個字符,而不是我之前想像的 916,657 個字符。我知道這一點是因為當遊標位於該行時,我按g + Ctrl+g並得到 81K 的列數。

後續1)這個問題"What is the best method of finding the line with the most columns?"和上面#2 一樣嗎?

後續2)當我打開文件並在螢幕底部看到以下行時,第二個數字意味著什麼:

在此輸入影像描述

我將此解釋為該文件有 14,871 行,並且至少一行有 916,657 列。我檢查過該文件確實有 14,871 行,但我無法理解第二個(916K)的用途。

答案1

第二個數字是整個檔案中的總字元數。如果你這樣做:

$ wc -l -c filename

您應該看到相同的兩個數字(行數和字元總數)。事實上,你可以這樣做:

:!wc -l -c %

這是一個名為文字過濾器下載),其中包括尋找最長線的函數。

或者您可以使用它來找到最長線的長度:

:echo max(map(range(1, line('$')), "col([v:val, '$'])")) - 1

那麼你可以像這樣使用這個數字:

/^.\{248\}$

答案2

一定有更好的方法,但以下也可以:

%s/./a/g         "Replace everything with 'a's
sort!            "Sort by column length
ggy$             "Go to first line (longest) and copy it
u                "Undo the sorting
/<c-r>"          "Search for the longest line
mm               "Mark it 'm'
u                "Undo the replace
'm               "Go to the mark - there!

答案3

Cam 沒有回答第一個問題,但檔案載入訊息中的第二個數字是檔案中的字元總數。

答案4

不是那麼以 vim 為中心,與其他一些答案類似,但對某些人來說可能更直觀。這假設您可以從 vim 中呼叫一些外部程式。

我的文件中有以下內容test_file

hello world
helloooooooooooooo world !!!
yo, world!
helloooOoooOooooOo World ! !

wc命令有時有一個-L選項可以列印最長行的大小。28 test_file是我的範例的輸出。

您可以使用 列印這 28 個字元行(及其行號)grep -nP ".{28}" test_file

2:helloooooooooooooo world !!!
4:helloooOoooOooooOo World ! !

您可以wc使用 來解析輸出cut。將它們放在一起並將一個命令貼到另一個命令中,它是:

grep -nP ".{$(wc -L test_file | cut -f 1 -d ' ')}" test_file

相關內容