In this post, I will demonstrate how to do find(search) and replace in vim.
2.1 Before you begin to find and replace
1) Open vim
For example, if you want to open a file named
README.md,just do as follows:
/ to goto
search command mode in vim
Just as following picture shows, there will be a
/ in the bottom-left corner of the window:
You can press
ESC to exit the
search command mode in vim.
2.2 How to find or search the vim?
If you have entered the
search command mode, you can just input the texts that you want to search in the file.
Just input the string you want to search and press
enter, then vim will jump to the first match in the file.
You can press
n to find next, or press
N to find previous.
If you want to search in case insensitive, you can search with
\c ,just as follows:
The above command will search for string
BSWEN with case insensitive, e.g.
bswen both match.
2.3 How to do replacement in vim?
After searching, you may want to do replace in vim, before replace, you must goto the
command mode in vim:
ESC and then input
: to goto
You can see that there is a
: in the bottom-left corner of the window, which indicates that you are in the
command mode, and vim is waiting for the command now.
The replace command format is as follows:
For example, if you use
replace_range, you will replace all the matching strings.
Commonly , we use
replace_tag, which means replace globally.
Now if you want to replace something , you can use the following command:
The above command will replace all
bar in the file.
If you want to replace in a range of lines, do as follows:
The above command will replace
bar from line 3 to line 14, inclusive.
If you want to replace carefully, you can do replace with confirmation:
The above command will prompt you to confirm for every replacement in vim.
replace with bar (y/n/a/q/l/^E/^Y)?
y to replace,
n to not replace,
a to replace all,
q to exit search mode, and
l to replace the current position and exit.
^Y are cursor movement shortcuts.
If you want to replace special characters ,do as follows:
In the above command, we replace
\r globally, the
\r means carriage return and new line in current file.
If you want to replace DOS style
\r\n with Unix style
\n, you can use the following command:
:set fileformat=unix :w
The above command replace all
2.3 Solution to replace without escaping special characters in vim
If you want to replace all
https://www.bswen.com, because the
/ is conflict with the
/ in search format, we can search and replace with special format:
In vim command mode,input this:
You can see that we use the comma as the seperator in search and replace command to avoid the confliction.
In this post, I demonstrated how to do find and replace in vim. That’s it, thanks for your reading.