[Practical.Vim(2012.9)].Drew.Neil.Tip98 学习摘要
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 invisibles
Tabs and Spaces
Whitespace 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.
上面的正则表达式利用了 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/">
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。