UNIX / Linux: vi / vim perform search and replace operation
Q. I’ve just installed CentOS Linux server and started to use vi text editor to make changes to config files. How do I perform search and replace operation using vi / vim text editor?
A. vi (vim) is not difficult to learn, the vi editor is well known and used for both writing code and editing config files.
VI search and replace command format
Simple format is as follows:
%s/old-string/new-string/
VI search and replace command examples
Let us say you would like to find a word called "foo" and replace with "bar".
First hit [Esc] key
Type : (colon) followed by %s/foo/bar/ and hit [Enter] key.
:%s/foo/bar/
Above command will replace first occurrence of word foo with bar on all lines. The % is shorthand for all lines.
To replace all occurrences of word foo with bar on all lines, use the g option (which indicates all occurrences on a line).
:%s/foo/bar/g
Note that the g can be replaced with a number 1,2,...N to change only the n'th occurrence on each line.
Use find and replace on line ranges (match by line numbers)
You can also make changes on range of lines i.e. replace first occurrence of foo with bar on lines 5 through 20 only, enter:
:5,20s/foo/bar/
Following command will replace first occurrence of foo with bar starting at the current line for the next 100 lines:
:.,+100s/foo/bar/
Match by words
Finally, you can match by words i.e. replace first occurrence of foo with bar starting at at the next line containing a word "test":
:/test/s/foo/bar/g
As usual you can specify ranges:
:/test/,/guest/s/foo/bar/g
Please note that all search/replace commands should be start with the [ESC]: keystroke combination only.
Subscribe to our free e-mail newsletter or RSS feed to get all updates.
You can Email this page to a friend.
Related Other Helpful FAQs:
- Change default Linux / UNIX text editor from VI to Pico
- How To Search Shell Command History
- Howto use grep command in Linux / UNIX
- Ubuntu Linux: Upgrade Linux Kernel
- Search all the Linux man pages for a particular command or text
Discussion on This FAQ
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!
Tags: find word replace with vi, line numbers, linux server, vi editor, vi search and replace, vim editor, vim text editor



August 11th, 2007 at 9:43 am
Hi,
I’m fairly new to vi and I’ve recently been making bulk changes on config files in vi using the following example;
:1,$s/sometexttoreplace/newtext
The $s means to the end of the file. I also found you need to escape characters like . with \.
However, I didn’t realise you could use the /g option to limit change to one line - that’s really helped me a lot!
May 12th, 2008 at 4:14 pm
You could also use regular expression. Suppose you have the httpd.conf
in this way:
simply do:
vim /etc/httpd/conf/httpd.confinside vim editor en command mode write: