標籤:global vim pattern
Delete Lines Containing a Pattern
Combining the :global
and :delete
commands allows us to cut down the size of a file rapidly. We can either keep or discard all lines that match a {pattern}
.
結合:global
和:delete命令可以快速的裁剪檔案。我們可以保留或著去掉匹配{pattern}的行。
測試檔案如下
Delete Matching Lines
What if we wanted to throw away everything except for the contents of each <a>
tag? In this file, the contents of each link appear on a line of their own, while every other line of the file contains either an opening or a closing tag.
So if we can devise a pattern that matches HTML tags, we could use it with the :global
command to reject any lines that match the pattern. These commands would do the trick:
如果我們要刪除除標籤<a>
包含內容之外的其他所有行,我們可以利用:global命令來刪除。
/\v\<\/?\w+> :g//d
If we run these two commands on the Vimcasts.org archive file, we ’re left with this:
在測試文檔中執行上面的命令,可以得到:
Show invisiblesTabs and SpacesWhitespace preferences and filetypes
The regular expression uses very magic mode (covered in Tip 73). It matches an opening angle bracket (\<), followed by an optional forward slash (\/?), and then one or more word characters (\w+) followed by an end-ofword delimiter (>). This is not an all-purpose tag-matching regex, but it’s good enough for this particular case.
上面的Regex利用了 verymagic模式。它匹配了<符號,前面加**進行轉置,後跟0個或1個/** ,同樣要用\進行轉置,隨後是一個或多個word,\w表示word,+表示1個或多個,最後還有>。
我們要找的就是標籤<某個word>
Keep Only Matching Lines
This time we ’ll switch things around. The :vglobal
command, or :v
for short, does the opposite of the :g command. That is, it executes a command on each line that does not match the specified pattern. The lines containing the URLs are easy to identify: they all contain the href attribute. We can select only those lines by running this command:
這次我們要在不匹配特定pattern的每一行文本執行命令。包含URL的行非常容易區分,都包含href屬性,我們就可以執行命令如下
:v/href/d
This can be read as “Delete each line that doesn’t contain href. ” The result looks like this:
這句命令可以翻譯為“刪除所有不含有href的行”,結果為
<a href="/episodes/show-invisibles/"><a href="/episodes/tabs-and-spaces/"><a href="/episodes/whitespace-preferences-and-filetypes/">
[Practical.Vim(2012.9)].Drew.Neil.Tip98 學習摘要