Saturday, March 24, 2012

VIM Tip: Not Containing Pattern (1)

Here is one tip I used last week when I tried to use VIM to match strings with a pattern not containing a pattern. The requirement is about a group of PL/SQL scripts. I have to update some lines in the script containing "tablespace xxx", where xxx is a table space name. There is one exception: don't change "tablespace temp".

I decided to use VIM Search and Replace feature to do the job. Since my search is case insensitive, first, I use the following command to tell VIM to ignore case for my search:

:set ignorecase

Then I used the following search pattern:

/tablesapce\s\+\(t\w\+\)\@!

This search is for any line containing word "tablespace" following any spaces, but the following word  beginning with "t". The following table explains some special characters in VIM:

ItemDescription
\swhitespace character
\+matches 1 or more of the preceding characters...
\(...\)enclosing a pattern as a group.
\wwork character
\@!not containing
\nthe matched pattern in the n pair of \(\), for example, \1 for the first matched group \(\).

Here I used group pattern with containing trick "\@!", which means that the word in the group does not  contain a word beginning with "t".  In my case, "tmp" is an example.

After I verified that the search result meets my requirement. The replace is used:

%s/\(tablespace\s\+\)\(t\w\+\)\@!/\1MyTablespace/gi

\1 is the matched the group 1, i.e., "tablespace" plus white space. Here gi means global and ignore case.

0 comments: