Once your familiar with finding files on your Ubuntu server you’ll quickly run into situations where you need to search within them from the command line.
Grep is an easy to use tool that quickly shows each line inside a file containing the keyword you feed it. Let’s get right to it!
Search lines containing 404 inside a web server log file.
grep "404" access.log
If you get too many results to be useful you can pipe the results into less which will start showing only the results that can fit on screen. You can continue scrolling through them line by line using enter or the up and down keys.
Pipe the results into less.
grep "404" access.log | less
Sometimes you just need to get a quick count of how many times something appears in a file.
Count the number of lines containing the word “failed”.
grep -c "failed" error.log
What if you need to search within a directory of files? The -r lets you search recursively through a directory. This can really come in handy searching through source code libraries.
Search within Ext JS 4 source folder recursively for Ext.data.proxy.Ajax
grep -r 'Ext.data.proxy.Ajax' src/
When you need to search through directories of files its often more helpful to see which files contain the keyword instead of the actual lines within the file. Use the -l option to output the path of each file containing a match.
Print out the file paths containing matches for Ext.data.proxy.Ajax
grep -r -l 'Ext.data.proxy.Ajax' src/
A few helpful options for tuning your search further are -i which performs case insensitive matching and -w which limits matches to the whole keyword instead of the default behavior which matches any line containing the keyword alone or as a segment of a another word.
Search recursively for the whole word dolly regardless of case
grep -r -i -w 'dolly' wordpress/
Piping Output From Other Commands into Grep
In addition to using grep by itself you can also quickly pipe the results from running other commands into grep to filter them by a keyword.
Filter memory usage stats to lines containing swap
free -m | grep -i 'Swap'
Let’s finish up with a more practical example. Let’s say you changed the default maximum file upload size in your php.ini config file but it’s still using the default value of 8M. You might have more than one php.ini file and you need to find out which one contains the default value of 8M.
Find all php.ini files that contain 8M and print matching line numbers.
sudo find / -name 'php.ini' | xargs grep -i -n '8M'
The special xargs command executes the output of the previous command before sending the results to grep. The -n option prints out the line number where each match occurs.
If combining different command lines tools is starting to make you feel like a linux pro, stay tuned to keep your command line muscles strong!