Grep How To – Part 1
Here 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.
[tags]Linux, Grep, How To, Tutorial[/tags]

May 14th, 2009 at 1:43 am
paylaşım için çok teşekkürler başarılar diliyorum
June 28th, 2009 at 7:33 am
Well I think it is useful to quote a possibility to search whole directory for some text in any of the files in that directory:
example: I want to find this stretch of text: “/dev/ttyU” in the /etc directory.
I do not know where exactly the file containing this text is, so I do:
# grep -r “/dev/ttyU” /etc
and the result is:
/etc/ppp/peers/cdma:/dev/ttyUSB0 # choose modem
/etc/ppp/peers/oskar:/dev/ttyU0 # device bound to T610
which tells me there are two files called “cdma” and “oskar” in the directory of /etc/ppp/peers/ that contain the string I was searching for.
I hope that is to some good!
cheers
Kolaloka
August 31st, 2009 at 9:42 am
Cool very cool .. tnx .. golod.com ..