vim技巧:刪除包含特定字符的行,刪除重複行並重新排序

vim技巧:刪除包含特定字符的行,刪除重複行並重新排序

下面介紹 vim 的一些使用技巧:

  • 刪除包含特定字符的行
  • 刪除重複行,並對所有內容重新排序

刪除包含特定字符的行

在 vim 中,可以使用 :g/pattern/d 命令刪除所有包含 pattern 模式的行。
例如,刪除所有以大寫字母 D 開頭的行,可以執行 :g/^D/d 命令。這裡的 ^ 表示匹配行首。

這裡的 :g:global 命令的縮寫,用 :help :g 命令查看它的幫助說明。部分關鍵說明如下:

:[range]g[lobal]/{pattern}/[cmd]
Execute the Ex command [cmd] (default ":p") on the lines within [range] where {pattern} matches.

即,:global 命令對匹配特定模式的每一行都執行所給的命令,有效的命令是vim命令行支持的命令,也就是以冒號 ':' 開頭的命令,但是輸入的時候不需要提供冒號。所以,上面的 d 對應

:d 命令,表示刪除一行。

使用 :help usr_10.txt 命令查看該用戶手冊,在 “10.4 The global command” 小節中對 :global 命令也有描述,可以參考。

刪除重複行,並對所有內容重新排序

在 vim 中,可以執行 :sort u 命令刪除重複行,只保留一行,並會對所有內容重新排序。
例如在文件中有如下的內容:

debug
checkout
release
hello.c
hello.c
release
hello.c
debug

執行 :sort u 命令後,會變成下面的內容:

checkout
debug
hello.c
release

可以看到,去掉了相同內容的重複行,只保留一行,所有行按照字母順序升序排列。


在 sort 後面加上感嘆號 '!' 會按照字母順序降序排序,也就是逆序。例如 :sort! u 命令。

使用 :help :sort 命令查看該命令的幫助說明,部分關鍵內容說明如下:

:[range]sor[t][!] [i][u][r][n][x][o] [/{pattern}/]
Sort lines in [range]. When no range is given all lines are sorted.
With [!] the order is reversed.
With [u] only keep the first of a sequence of identical lines (ignoring case when [i] is used). Without this flag, a sequence of identical lines will be kept in their original order. Note that leading and trailing white space may cause lines to be different.

即,:sort 命令本身對文件行進行排序,默認不會去掉重複行,加上 u 參數來去掉重複行。


分享到:


相關文章: