It never fails that I find myself hunting for a way to search for a particular text string in files. Usually I know the file, but often times I also find that I am completely unsure what file contains the string. Or while I am writting some code I need to find how many files use a certain function.
I know that using grep is the best way to search on a Linux server, so I start there. Here is the command syntax:
grep "text string to search for" /path/to/search
To search for a string called “myFunction” in all text files located in /var/www/html/*.php use:
grep "myFunction" /var/www/html/*.php
To search recursively in all sub-directories you would alter the command by adding the -r option:
grep -r "myFunction" /var/www/html
Now you have probably noticed that grep prints out the matching lines containing your string, but you may also need the filenames of the files containing the string instead. You can use the -H option to narrow the output the filename followed by the line containing your search string, like so:
grep -H -r "myFunction" /var/www/html
This would output something like:
... your_file.php: line containing myFunction ..
To print out just the filename you can cut command like this to clean the output further: (Note the one after the f, not an L)
grep -H -r "myFunction" /var/www/html | cut -d: -f1
The new cleaner out put would be like:
... your_file.php ...