Vim has a quick find and replace functions for your text editing. We will look into each types of find and replace.
To find by keyword, go to the command mode and begin with /
command. Provide the keyword after that and press ENTER. The pattern is something as such:
/keyword
/keyword\ that\ has\ space\ or\ interpretive\ characters
Once you press ENTER, vim will either immediately jump to the next keyword from your cursor or reporting keyword not found.
to navigate through all the searches, you press:
n
for forward directionN
for backward directionTo find by line number, go to the command mode and begin with :
command. Provide the line number after that and press ENTER. The pattern is something as such:
:1
:1000
Once you press ENTER, vim will either jump to that line or to the last line (when you provide line number larger than the file has).
to navigate through all the searches, you press:
n
for forward directionN
for backward directionVim also supports find and replace function. However, there are different types of find and replaces. The general pattern is:
:<range>s/<keyword>/<replacement>/<options>
If you notice, the /keyword>
is similar to find by keyword. Hence, the find by keywords rules applies. I documented the following based on their elementary functions. You can combine them to create your very own functions. Example, to find and replace all occurrence, from line 62 to 2000, with confirmation, from keyword yawn
to raise to sunshine
, I do:
:62,2000s/yawn/raise\ to\ sunshine/gc
Confusing? Do not worry. Just remember the following elementary functions will do. Let the experience build up and you can build your own one.
To replace the first occurrence, supply <options>
without the global g
flag. Example:
:s/foo/bar/
To replace the last occurrence, supply a prefix to your <keyword>
with .*\zs
. Example:
:s/.*\zsfoo/bar/
To replace all occurrences, supply <options>
with the global g
flag. Example:
:s/foo/bar/g
To prompt confirmation interactively, supply <options> with the global c
flag. Example:
:s/foo/bar/c
:s/foo/bar/gc
To find and replace the keyword in the current line, just set <range>
to nothing. Example:
:s/foo/bar/
To find and replace all keywords from line 1 to the last line, set the <range>
to %
. Example:
:%s/foo/bar/
To find and replace all keywords from current cursor point to last line, set the <range>
to ,$
. Example:
:,$s/foo/bar/
To find and replace all keywords within a bounded line number range, set the <range>
to start,stop
. Example:
:5,12s/foo/bar/
To find and replace with precise keyword matching, set the <keyword>
with the <...>
boundary. Example:
:s/<foo>/bar
To find and delete the keyword, set the <replacement> to nothing. Example:
%s/foo//
There are more search functions available at https://vim.fandom.com/wiki/Search_and_replace. However, to reduce complexity, my guide stops here since these should be suffice for normal day jobs. Feel free to explore the wiki for more fancy functions.