How to find and replace a text string in all files on your cPanel / WHM / Linux / Unix server

H

If you need to quickly find and replace all occurrences of a string of text, the Linux shell is a very helpful too. To do this, we’ll be using the find, xargs, and sed commands. Find is pretty self-explanatory, and sed is short for “stream editor”, which allows you to filter and transform text. xargs is a command that takes in input and executes your chosen command on it – and in our following example, allows you to run the same command on each of the things the find command found.

Here is the command:

find /home/username/public_html/ -type f -name ‘*.php’ -maxdepth 4 -print0 | xargs -0 sed -i ‘s/ancientkg.pay/ancientsec.pay/’

In English, this means to find (find command) in /home/username/public_html/ any file (-type f) of file extension .php (-name ‘*.php’). It searches for 4 levels of sub-folders (-maxdepth 4) after your specified location, and edits files in place (-i). The arguments -print0 (for the find command) and -0 (for the xargs command) must be used together. What it does is separate file names with a 0 (NULL) byte so that file names containing spaces or newlines won’t cause errors.

To limit your search to only the current folder and not search through any sub-folders, use the -maxdepth 0 option.

Similar Posts:

About the author

Alvin Poh

I've over 17 years of entrepreneurship experience, having built a tech company to be the top in the country, which was subsequently acquired for an 8-figure sum. As CEO, I led the company through robust growth to 150 employees across 4 countries. After the acquisition, I embraced minimalism, sold off my personal possessions, and started living around the world.

Read more about my story here.

Add comment

By Alvin Poh

About Author

I've over 17 years of entrepreneurship experience, having built a tech company to be the top in the country, which was subsequently acquired for an 8-figure sum. As CEO, I led the company through robust growth to 150 employees across 4 countries. After the acquisition, I embraced minimalism, sold off my personal possessions, and started living around the world.

Read more about my story here.