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

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/’

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.

Leave a Reply

Your email address will not be published. Required fields are marked *