Grep examples and tricks
Grep uses regular expressions. So, that might be a good place to look for info.
(I've got a scribble for regex that might be useful, link at the right of this page.)
And a few examples and notes:
-
Windows based Grep GUI tool, OSS, by the Tortoise SVN guys:
-
https://code.google.com/p/grepwin/ - works great, I only wish it could show a few leading and trailing lines... but generally awesome.
-
A useful PDF: http://www.cs.gsu.edu/~cscyip/csc3320/grep.pdf
-
to search all files in a directory, including subdirectories for all files with the phrase "Edit Message" in it:
grep -r "Edit Message" *
(where -r is the recursive flag)
-
you can use grep without quotes around the search phrase, sometimes. But to be safe, use double quotes. For instance, in this example, quotes are needed, or else grep just doesn't work:
grep "a a" pgde.txt - this one searches the text file pgde.txt and prints every line containing a space a.
-
the escape character in grep is backslash, i.e. "\" - you need to put one of these before each quote (and some other characters) in your search terms.
-
this example uses two greps piped together.
-
first, cat reads the file (my Apache log, actually)
-
the first grep grabs all lines with perceptus in it (i.e. access to www.perceptus.ca or one of it's subdomains).
-
the second grep filters out lines from my workstation. The -v option tells grep to show lines that do NOT include the specified text, "192...".
-
thus I get a screen full of web accesses to *.perceptus.ca that did not come from my workstation.
-
cat access_log | grep perceptus.ca | grep -v 192.168.81.91
-
Grepping for quotes:
c:\grep -v ' OnHand=\"0' InventoryLocation.sql > InventoryLocationHacked.sql
-
note, the extra space before OnHand is required to filter out terms like MaxOnHand, MinOnHand!
-
"C:" just points to the current c: folder which has a Windows port of Grep in it (it saves me from typing a long path)
-
A slash is needed in front of the special character, ".
-
Grepping a log file to pull up applicable lines in the text file AND lines before and after it:
-
c:\tools\gnu\grep timed -B 5 -A 5 ping_log.txt > ping_log_timeout.txt
-
Greps a basic log of pings and timestamps. Looks for the text "timed" (short form of "Request Timed Out"). Returns 5 lines "B"efore and "A"fter. Pipes output to a new text file.
-
Grepping for a list of strings, e.g. hotmail.com or live.com or msn.com:
-
cat /var/log/maillog.1 | grep 'hotmail.com\|live.com\|msn.com' | grep 20:11
-
I can't explain the extra slash, it was on some sample page, I guess the pipe character is reserved.
Tags: tools, text, manipulate, filter, grep, regex,
>>
Leonard Chan's Homepage
>>
Scribble Web
>> Grep examples and tricks