How to Replace Multiple occurrence of String in a File on Linux

(Bibin Wilson) #1

It is always better to find the number of string occurrences in the file.

For example, if your file is settings.xml and you want to find the no of occurrences of string name username. To do that, you can use the following syntax.

grep -o 'search_string' /path/to/file |  wc -l

For example,

grep -o 'username' settings.xml |  wc -l

The above command will give the total number of occurrences. Once you are sure about replacing all the occurrences, you can use the sed command for replacing the text.

For instance, if you want to replace username with the settings.xml file to user_name, you can use the following syntax.

sed -i 's/original/new/g' filename

s - substitution
original = full length or a regular expression for the string that has to be replaced.
new = new string for replacement.
g = global (to replace all the occurrences)

For example,

sed -i 's/username/user_name/g' settings.xml