vim: Search & Replace

The vim search and replace command is of the form:

:range s[ubstitute]/pattern/string/cgiI


The command for each line in the range replaces a match of the pattern with the string.

Where range can be:
number an absolute line number
. the current line
$ the last line in the file
% the whole file. The same as 1,$
't position of mark "t"
/pattern[/] the next line where text "pattern" matches.
?pattern[?] the previous line where text "pattern" matches
\/ the next line where the previously used search pattern matches ("\" "/")
\? the previous line where the previously used search pattern matches
\& the next line where the previously used substitute pattern matches

Please note:
  • You can mark your current position in the text by typing "mt", where "t" can be any letter, and use it as a mark later defining the line address.
  • If no line range is specified the command will operate on the current line only.
And where pattern consists of anchors, metacharacters and quantifiers:
Anchors:
\<>
Word boundary de-limiters
^
Beginning of the line
$
End of the line

Metacharacters:
.
any character except new line
\s
whitespace character
\S
non-whitespace character
\d
digit
\D
non-digit
\x
hex digit
\X
non-hex digit
\o
octal digit
\O
non-octal digit
\h
head of word character (a,b,c...z,A,B,C...Z and _)
\H
non-head of word character
\p
printable character
\P
like \p, but excluding digits
\w
word character
\W
non-word character
\a
alphabetic character
\A
non-alphabetic character
\l
lowercase character
\L
non-lowercase character
\u
uppercase character
\U
non-uppercase character


Quantifiers may be greedy or non-greedy.

Here are the greedy ones: (here n and m are positive integers)
*
matches 0 or more of the preceding characters, ranges or metacharacters .* matches everything including empty line
\+
matches 1 or more of the preceding characters...
\=
matches 0 or 1 more of the preceding characters...
\{n,m}
matches from n to m of the preceding characters...
\{n}
matches exactly n times of the preceding characters...
\{,m}
matches at most m (from 0 to m) of the preceding characters...
\{n,}
matches at least n of of the preceding characters...

and here are the non-greedy quantifiers:

\{-}
matches 0 or more of the preceding atom, as few as possible
\{-n,m}
matches 1 or more of the preceding characters...
\{-n,}
matches at least 1 or more of the preceding characters...
\{-,m}
matches 1 or more of the preceding characters...

Finally the "search and replace command" may be followed by:
c Confirm each substitution
g Replace all occurrences in the line (without g - only first).
i Ignore case for the pattern.
I Don't ignore case for the pattern.


This is just an extract from:
http://larc.ee.nthu.edu.tw/~cthuang/vim/files/vim-regex/vim-regex.htm
For detailed usage visit the link.


No comments:

mishrav's shared items