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 ...
2 responses to “Finding a text string inside a file on a Linux server”
Hi, I found this very useful 🙂 Thanks.
I am very new to Linux.. can you explain why I have to put in the whole path to serach?
grep -H -r “myFunction” /var/www/html | cut -d: -f1
I thought I could leave out the /var/www/html if I am already in /var/www/html?
Really helped me a lot 🙂 thanks…..