Grep How To - Part 1
February 7th, 2007Here are a few little tid bits that I use on a daily basis with the awesome Grep command line tool.
Grep allows you to search files for symbols or strings (groups of characters like words) and will return the files that the search sting is found in. For example you want to search a website’s access log file for a recent traffic that came from a search engine. Most search engine referral urls have a question mark in them. The Grep command would look something like this:
grep [search string] [file name]
grep “?” /www/logs/golod.com-access.log
I use the double quotes around the question mark so that grep doesn’t get confused by a symbol, the third part is the location of the file on my server that I want to search.
Now let’s say you get a slew of information and you really only want to see searches that came in on a specific date. Since apache is configured to format my log files with a date like 07/Feb as the date I would “pipe” the results or pass them to another grep command. This looks like:
grep [search string] [file name] | grep [2nd search string]
grep “?” /www/logs/golod.com-access.log | grep “07/Feb”
This essentially passes the results of the first grep search to the 2nd grep search for further refinement.
One last thing that I use all of the time with Grep is the -v operator. Adding -v to your grep statement allows you to eliminate results that match a certain search string. Using our example:
grep [search string] [file name] | grep [2nd search string] | grep -v [search string]
grep “?” /www/logs/golod.com-access.log | grep “07/Feb” | grep -v “yahoo”
This would give us the same results as before, but it would remove any of the results that had the string yahoo anywhere in them.
Hopefully, this helps.
