linux command line search and replace

 

In linux command line, search recursively through directories, looking in all files for a particular string, and replace that string with something else:

find ./ -type f -exec sed -i 's/string1/string2/' {} \;

Where string1 is the search string and string2 is the replace string.

Examples that replace a user name within all sub-folders of the  home directory (to aid in copying a user’s settings)

find /home/tech/ -name ".*" -type f -exec sed -i 's/tech/user/' {} \;

For replacement strings that include special characters like forward and back slashes:

find ./ -type f -exec sed -i 's|F:\\Home\\Libre\\MACROshortcut|\/mnt\/local-files\/Libre\MACROsymlink|g' {} \;

For a bash script maybe:

#!/bin/bash
STRING1=tech
STRING2=user
find /home/tech/ -type f -exec sed -i 's/$STRING1/$STRING2/' {} \;

And to run the bash script asking for input:

#!/bin/bash
STRING1=tech
echo -n "What is the new user name?"
read STRING2
find /home/tech/ -type f -exec sed -i 's/$STRING1/$STRING2/' {} \; echo "<$STRING1> has been replaced with <$STRING2>"