Vim, an acronym for Vi IMproved, is an open-source, multi-modal text editor that comes with most UNIX systems. It offers a rich set of features and enables efficient text editing by using keyboard shortcuts. In this blog post, we’re going to delve into one of Vim’s powerful features: finding and deleting lines with specific patterns.
The Global Command
One of the most potent tools in Vim is the Global command, represented by :g. This command is used to execute a command on all lines, or on all lines that match a certain pattern. The delete command, d, is often used in combination with the global command for deleting specific lines.
For instance, to delete all lines containing “profile”, you would use:
:g/profile/d
By removing the /d, you can preview which lines will be deleted without actually deleting them:
:g/profile
Dealing with Whitespace
If you want to delete all lines that are empty or contain only whitespace, the following pattern is used:
:g/^\s*$/d
Here, ^ represents the start of the line, $ represents the end of the line, \s is a whitespace character, and * means zero or more of the preceding character. So ^\s*$ matches a line that is either completely empty or contains only whitespace characters.
Inverse Matching
Vim allows you to delete all lines that do not contain a pattern using g! or its equivalent v. Suppose you want to delete all lines that are not comment lines in a Vim script. Here, we’re considering lines starting with ", after zero or more whitespace, as comment lines:
:g!/^\s*"/d
Or using v:
:v/^\s*"/d
Using OR in Patterns
You can use the OR operator (\|) to match multiple patterns. For instance, if you want to delete all lines except those that contain “error”, “warn”, or “fail”, you can do it as follows:
:v/error\|warn\|fail/d
More Complex Example
Let’s look at a more complex example. Suppose you want to delete all lines that start with a hash (#) but exclude those that contain “important”. You can achieve this with the following command:
:g/^#\s\+important\@!/d
In this pattern, ^# matches lines that start with a hash, \s\+ matches one or more whitespace characters, and important\@! is a negative look-ahead assertion that checks if the line does not contain “important” after the hash and spaces.
Conclusion
In this post, we’ve explored various ways to find and delete lines in Vim using pattern matching. While these commands might seem complex at first, with a little practice, you can harness the power of Vim to edit your files efficiently. Remember, the best way to learn Vim is by using it.
Buy Me a Coffee