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 

Replace String in Multiple Files Linux Bash

We can copy all file paths into a file. Let's call the file name as `list`.
There are multiple ways of creating `list`. Here are some.
ls > list
grep -l "FIND_STRING" file_path > list
In file_path you can mention something like *.java for example to search all java files alone.

Below is the bash script which you can put in an executable file and run.
#!/usr/bin/ksh
for var in `cat list`
do
sed -i "s/FIND_STRING/REPLACE_STRING/g" $var
done
UA-39217154-2