Using sed, perl or vi to search in replace
The ability to search and replace strings in text files can save time, particularly in cases where a string needs to be changed multiple times within one file or even multiple files.
For example, a previous admin has written several PHP scripts which all have the IP address of a server hard-coded throughout the script.
Now the IP address has changed and the script needs to be updated. While setting the IP address to a variable would have been ideal, the scripts can be quickly updated using search and replace methods.
There are a number of ways to search and replace strings in text files on Linux servers.
Search and replace every instance of OLDSTRING in filename.php with NEWSTRING.
Using sed:
sed -i -e 's/OLDSTRING/NEWSTRING/g' filename.php
Using perl:
perl -pi -e 's/OLDSTRING/NEWSTRING/g' filename.php
Using the vi editor:
:%s/OLDSTRING/NEWSTRING/
(use :wq! to save the file and exit the vi editor after the change)
If you need to change all files in the same directory, wildcards can be used, such as *.php
sed -i -e 's/OLDSTRING/NEWSTRING/g' *.php
If the files that need to be changed reside in multiple subdirectories the above commands can be combined with find and xargs to make the changes recursively. Caution should be used when using any search and replace method (particularly recursive changes involving multiple files) as a mistake can result in undesired alterations and data loss. Having a backup ready is highly recommended.
Using sed with find and xargs for changing files recursively:
find -name "*.php" -print0 | xargs -0 sed -i -e 's/OLDSTRING/NEWSTRING/g'
This command will recursively search for any file matching "*.php"
starting from the current/working directory and change all instances of OLDSTRING to NEWSTRING in each of the files found.