I want to replace a string that is in multiple files in a Linux folder.
Problem
How to replace a string in multiple files in a Linux folder?
Solution
For example, I want to search for the database.php word scattered across multiple PHP files in a folder, and I use the Linux command below:
grep -R database.php *

In the image above, the word is scattered across multiple Linux files and in different Linux folders. So that you don’t go into the file that is in a different folder one by one and then change the word database.php, for example, to config.php manually, but you can run the command below:
find . -type f -name "*.php" -exec sed -i 's/database\.php/config.php/g' {} +
which results in the image below:

In the image above, you can see that the word has been successfully changed to config.php, which is not found when you search for database.php. If you just change the database.php word to config.php in a folder, as shown in the image below:

You can use the format below to replace the word:
sed -i 's/old_word/new_word/g' filename
So you can run the command below to change the word database.conf to config.php
sed -i 's/database\.php/config.php/g' *.php
So it will look like the image below:

In the image above, you can see that the string database.php has been changed to config.php.
Note
If you’re still unsure about running the two commands above to change a word scattered across multiple files, you can preview the results you expect. For example, if you want to preview the results first before you permanently change the changes in a folder, then you can run the command below:
sed 's/database\.php/config.php/g' *.php | grep database.php
and the result will be as shown in the image below:

And if you want to automatically back up when changing a string in multiple files, then use the command below:
sed -i.bak 's/database\.php/config.php/g' *.php
Then the result will be as shown in the image below:

In the image, you can see that files that have the word database.php are automatically backed up to files with the .bak extension.
References
unix.stackexchange.com
askubuntu.com
stackoverflow.com

