October 31, 2014
 
 
RSSRSS feed

Advanced Tips for Search-and-Replace in Linux - page 2

Search and Replace Power Tools

  • September 29, 2009
  • By Juliet Kemp

Sometimes it can be useful to use a complemented character set. This is like a range, except that what you match is any character except the ones in the range. So [^aieou] would match any character except the five vowels. One use of this might be to find quoted sentences (e.g. "this quoted sentence") in a piece of text. In Vim, use this:

/"[^"]\+"
Note that this is just a search, not a search-and-replace, so you just use / at the start of it. In Emacs, use:
C-M-s "[^"]+"
(The long version of C-M-s is M-x isearch-forward-regexp). This pattern looks for the " character, followed by at least one of any character except the quote character ([^"]\+, or [^"]+ in Emacs where you don't need to escape the +), followed by a final quote character.

In Emacs, this will also handle multi-line quotes, since in Emacs, when using a complemented character set, newline is included as one of the characters that will match (unless it's newline itself that is part of the group of characters not to be matched!). However, in vim, as in most other tools, newline isn't matched by a complemented character set. So to make this pattern match two-line quotes as well as one-line quotes, use this:
/"[^"]\+[\n]*[^"]\+"
To match three-line quotes, you'd need to add the "zero or more newlines plus one or more non-quote characters" part of this pattern another time before the closing quote.

This is just a quick guide to a couple of useful things you can do with regular expressions: the scope is immense. It's well worth spending a little time getting to grips with them, and it can be quite good fun. Have a go yourself, and soon you too will be familiar with leaning toothpick syndrome (\/\/\/\)!

Sitemap | Contact Us