Thursday, May 10, 2018

Find and Replace in vi Editor

How do we find and replace a string in vi Editor? 
Open the file in vi and use this: 
:%s/FIND_PATTERN/REPLACE_STRING/ 
This will replace only the first occurrence of that string in each line. If you want to replace all occurrence, use the below: 
:%s/FIND_PATTERN/REPLACE_STRING/g 
How to take one string pattern from find pattern and use it in replace string? 
In such case, you have to add that string pattern inside \( and \) in the find pattern and use \1 in replace string in the position where you want to replace it. 
For Example: 
Let's say you wan't to take all abc_NAME.test (NAME can be any name) and put it differently as lmn_NAME.test. 
:%s/abc_\(.*.test\).*/lmn_\1/ 
You can also do in multiple times. Only the order in which you open \( matters. It can even be nested. In replace you can use \1 \2 ]3 ... etc 
UA-39217154-2