Vi and Vim is very powerful editor in Linux operating system. I already discussed vi, vim commands in my previous tutorial.
In this post i’ll discuss search and replace feature in vi,vim editor. Like all other editor vi also provides this facility. Let’s check how to search and replace any word,text in vi,vim editor.
Search in VI, VIM Editor
How do you search any word or text in vi. By simply using slash and question mark (/ and ?) and type the word you are searching.
Linux Commands with Examples .
Before using these commands make sure you’r vi editor in normal mode. If it’s not press <ESC> so that it comes in normal mode.
a) Search string forward using slash (/).
1 2 3 4 5 6 7 8 9 10 11 |
/* Syntax for searching */ /STRING /* Search foo */ /foo /* Search area */ /area |
To continue searching same word press n.
b) Search string backward using question mark (?).
When you use question mark (?) and string it will start searching string from bottom of the file.
1 2 3 4 5 6 7 |
/* Start searching from the end of the file. */ ?STRING /* Start searching foo word from the end of the file. */ ?foo |
To continue searching word from opposite direction press shift+n .
Search and Replace in VI, VIM Editor
Syntax of search and replace –
1 2 3 4 5 6 7 |
/* Search and replace for first occurrence of word */ :s/search/replace /* Search and replace globally (for every occurrence of file) */ :s/search/replace/g |
Now we have to find all the occurrence of foo in a file and replace with bar.
1 2 3 |
/* Find all occurrence of foo and replace with bar. */ :s/foo/bar/g |
Find each occurrence of product and replace it with product_desc.
1 2 3 |
/* Find each occurrence of product and replace with product_desc. */ :%s/product/product_desc/g |
Ask for confirmation before replacing. Replace all occurrence of product to product_desc, but it asks for confirmation.
1 2 3 |
/* Search and replace with confirmation. */ :%s/product/product_desc/gc |
Insensitive find and replace.
Find product (Product, PRODUCT, proDUCT and so on) and replace with product_desc.
1 2 3 |
/* Insensitive search and replace. */ :%s/product/product_desc/gi |
Recommended Books for Vi,Vim Editor
Vi, Vim Editor Books on Amazon.com
Conclusion
I hope this short tip will be helpful for you. If you want to add some more tips please let us know through your comments.