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
the Combine and: Delete command allows you to quickly crop files. We can keep or remove lines that match {pattern}.
The test files are as follows
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 all 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 this matches HTML tags, we could use it with the :global
command to reject any lines that MATC H the pattern. These commands would do the trick:
If we want to delete <a>
all the rows except the label, we can use the: global command to delete.
/\v\<\/?\w:g//d
If We run these-commands on the vimcasts.org archive file, we ' re-left with this:
Execute the above command in the test document to get:
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 Charac Ters (\w+) followed by an End-ofword delimiter (>). This is a all-purpose tag-matching regex, but it's good enough for this particular case.
The above regular expression takes advantage of the verymagic pattern. It matches the < symbol, preceded by a * * for transpose, followed by 0 or 1 /**, also with \ to transpose, followed by one or more word,\w means word,+ represents 1 or more, and finally there is >.
All we're looking for is a label < a word>.
Keep only Matching Lines
This time we ' ll switch things around. The :vglobal
command, or for short :v
, does the opposite of the:g command. That's, it executes a command on the all line this does not match the specified pattern. The lines containing the URLs is easy-to-identify:they all contain the href attribute. We can select only those lines by running the This command:
This time we're going to execute the command on every line of text that doesn't match a particular pattern. The line containing the URL is very easy to distinguish, including the href attribute, and we can execute the command as follows
:v/href/d
This can is read as "Delete each line that doesn ' t contain href." The result looks like this:
This command can be translated as "delete all rows without href" and result in
<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 Study Summary