Matching Newlines in Vim
In a recent article I wrote about using regular expressions in editors, I mentioned the fact that by default, Emacs will match newlines when using a complemented character set, and vim won't. A helpful reader, Tim Chase, contacted me to share a way around this.Tip of the Trade: Want vim to share newlines? You're only two characters away.
It's pleasingly straightforward: All you do is to add _ in front of the character class you want to match. This will then match the character class plus newline. So to search for a word character:
/ (from command mode) is the search command in vim, and w indicates a word character. So, to search for a word character or newline:
Note that you don't have to use backslash again for the w. In effect, _w is treated as a single character class definition.
The example I used in my article was looking for a single-line quote, for which you can use
This searches for a quote mark, at least one (+) of any character except a quote mark (the complemented character class [^CHAR] means "any character except CHAR), and then another quote mark. To extend that to multiple lines, all you need do is add _ in front of that complemented character class:
Straightforward and very useful. It's nice as well to have the option of including or not including newlines. Thanks to Tim for the heads-up! Yet another example of however long you have been using a Linux tool, you can always learn new things about it.
Have you found any unusual workarounds in Linux or Unix tools you regularly use? Please comment below and let me know.
Juliet Kemp has been messing around with Linux systems, for financial reward and otherwise, for about a decade. She is also the author of "Linux System Administration Recipes: A Problem-Solution Approach" (Apress, 2009).