[Linux](EN) Replace string in vi(or vim)
Change strings in vi or vim.
Environment and Prerequisite
- Linux base system
- Bash shell(/bin/bash)
- vi or vim
vi(or vim) string replacement
Basic Form
Format
:%s/[original string]/[string to replace]/[options]
- Use above form with various options.
- Options can be used in multiple.
- If omit
%
in above command, only current cursor line string will be replaced.
Options
g
: Replace all matched strings(not only first occurrence in each line).
ThisThisThis -> testtesttest
:%s/This/test/g
c
: Check before replacement.
ThisThisThis -> testThisThis
~
replace with test (y/n/a/q/l/^E/^Y)?y
:%s/This/test/c
i
: Don’t care upper and lower case.
ThistHisthIs -> testtesttest
:%s/This/test/ig
Examples
- Make test text file.
$ vi test.txt
This is test string. This is it!
This is second string.
Example 0 - Replace first ‘This’ to ‘tHIS’ in current line
- Just remove
%
like below.
tHIS is test string. This is it!
This is second string.
~
~
:s/This/tHIS
Example 1 - Replace first ‘This’ to ‘tHIS’ in each line
- If there is no option, replace string in one line and move to next line. So, it moves to next line even though there are more matched strings after replacement.
tHIS is test string. This is it!
tHIS is second string.
~
~
:%s/This/tHIS
Example 2 - Replace all ‘This’ to ‘tHIS’
- Replace all matched strings using
g
option.
tHIS is test string. tHIS is it!
tHIS is second string.
~
~
:%s/This/tHIS/g
Example 3 - Check every time when replacing
- Check every time by using
c
option. - Use
g
option to replace all matched strings. - Current example give input in y->n->y order.
this is test string. This is it!
this is second string.
~
~
replace with test (y/n/a/q/l/^E/^Y)?y
:%s/This/tHIS/cg
Example 4 - Replace ‘This’ to ‘tHIS’ while ignoring upper and lower case
- Use
i
option to ignore upper and lower case. - Use
g
option to replace all matched strings.
tHIS is test string. tHIS is it!
tHIS is second string.
~
~
:%s/this/tHIS/ig