Vim Tips Wiki
Line 59: Line 59:
 
S(<regex>)[<replacement>]<flags>
 
S(<regex>)[<replacement>]<flags>
 
</pre>
 
</pre>
<q-args> produces an escaped and enclosed in double quotes string, problems with unicode are solved (I hope so) by "use encoding" statement.
+
"<q-args>" produces an escaped and enclosed in double quotes string, problems with unicode are solved (I hope so) by "use encoding" statement.
   
 
----
 
----

Revision as of 03:43, 16 December 2009

Tip 393 Printable Monobook Previous Next

created 2002 · complexity intermediate · version 5.7


1. Verify with :ver that +perl or +perl/dyn is compiled in.

2. Install Perl if necessary. On Windows, ActivePerl is required.

3. Type :perldo s/searchme/replaceme/g

Note: +perl/dyn doesn't seem to be necessary.

Comments

Or if you have ruby compiled in (look for +ruby in :ver output):

:rubydo sub! /pattern/,'replacement'

The advantage of this tip is that when you know Perl regex well it's easier to write Perl regex than vi regex. Either is find for simple expressions, but when the expressions get more complex its much easier to work with the syntax you know the best.


Perl regexes also have a different set of "special characters".

For example, the brackets () are special characters that automatically do grouping and capturing in perl. In a vi regex, they need to be escaped \( \) before they'll turn special.


Keep in mind that :perldo is not always enough. Just try to replace something with a newline (:perldo s/<text>/\n/<CR>). I get ^@ character instead of a line break. Yeah, i asked for it but not what I wanted.

In this particular case, just use the old "perl pie":

:%!perl -pi -e 's/<text>/\n/'

VimTip6


Script to search using PCRE in Vim: http://groups.yahoo.com/group/vim/message/49561


I know this is a small thing, but you might check out "\v", aka very-magic as a way to make the regular expressions less annoying and more perl-like. It would be nice if I could put set very-magic in my vimrc.


You can also define new command like this:

:command -range=% -nargs=+ S <line1>,<line2>!perl -pi -e "use encoding 'utf8'; "s<q-args> 2>/dev/null
" Example usage:
S(<regex>)[<replacement>]<flags>

"<q-args>" produces an escaped and enclosed in double quotes string, problems with unicode are solved (I hope so) by "use encoding" statement.