Tuesday, January 27, 2009

Vim tips: The basics of search and replace

Search:
1. /searchstring search forward through the file and ?searchstring search backwards through the file.
2. After running a search once, we can repeat it by using n in command mode, or N to reverse direction.
Replace:
syntax : [range] s/search/replace
1. The range is optional; if we just run :s/search/replace, it will search only the current line and match only the first occurrence of a term. We can add a range like:
:8, 10 s/search/replace/g
Without adding g, the search will match only the first instance of a string in any given line.
2. If you want to search an entire file, you can use % to indicate that as the range. If you wish to be asked for confirmation before Vim makes a substitution, add the confirm (c) option to the end of the search and replace command. (i) option will ignore case for the search pattern. (g) option will replace all occurrences in the line. Without this, Vim replaces only the first occurrences in each file.
:%s/search/replace/gc
Where you land:
1. To land on the last character in the matched string, add /e to your search: /string/e
2. To specify a cursor offset by line: /string/+2 or /string/-2
3. To specify a cursor offset by the beginning of the string or the end of the string: /string/s+2 or /string/e-3

No comments: