Grep on Windows
For the longest time I’ve been using Agent Ransack and it has served me very well. But today when I wanted to copy some text from the search results pane, I found that I could not do so. Therefore it was time to look for an alternative file searching utility …
I had heard good things about grep and thought I’d give it a try. Googling for “windows grep” gave me Windows Grep as the top-ranked result. I tried it and found that I could in fact copy text from the results view. Unfortunately Windows Grep is shareware and its website states that “… should you … use it beyond an initial evaluation period of 30 days you are both legally and morally obliged to pay the license fee.” So I decided to go for the original grep: GnuWin32 Grep for Windows.
It’s back to the command line!
What I wanted to do was to look for occurrences of MessageID = nnn in all files in all subdirectories. I downloaded the .chm help file from the Grep for Windows SourceForge homepage and went straight to the “Usage” section.
How do I search directories recursively?
grep -r ‘hello’ /home/gigi
searches for `hello’ in all files under the directory `/home/gigi’
Looks simple enough. I tried it – hmm, didn’t work, when it definitely should produce lots of results. After some experimentation I found out that doublequotes should be used instead of singlequotes, and “*.*” should be used instead of the directory name, like so:
grep -r "MessageID.*=" *.*
OK. Now to output the results to a file. I tried:
grep -r "MessageID.*=" *.* > grep.out.txt
Nothing seemed to be happening … and my PC was bordering on behaviour best described as “hanging”. So I resorted to good ol’ Ctrl-C. I also noticed that grep.out.txt seemed to be really big – a few hundred megs in size. After doing this a few times I figured out that grep was stuck in an infinite loop: it was writing results to grep.out.txt, and at the same time, reading grep.out.txt! So the following is what finally worked for me:
grep -r "MessageID.*=" *.* > ..\grep.out.txt
So there you have it. A Unix command on Windows, complete with all sorts of pitfalls for newbies, but very fast and powerful once you get the hang of it.
Note: In actual fact, what I did was
grep -iInr "MessageID.*=" *.* > ..\grep.out.txt
which also ignores case, eliminates the “Binary file matches” messages, and prints line numbers.
3 Responses to “Grep on Windows”
1 Ady 25 April 2008 @ 11:11 pm
Do you know that there is a utility in Windows called “findstr” ? Not sure whether it’s available on XP. I am on Windows 2003 Server now.
Searches for strings in files.
FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]
[/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]
strings [[drive:][path]filename[ …]]
2 Gunja Farmer 28 April 2008 @ 9:46 am
Riveting stuff habeeb…as usual
3 dirn 29 April 2008 @ 2:03 am
perbincangan tahap2 dewa…
Comments: