Datamal Blog

Wednesday, September 22, 2004

Searching files with Grep on Windows using Cygwin


The following is an extract taken from Bruce Eckel's weblog relating to this title.

Just go to http://www.cygwin.com and follow the directions, and you'll end up with the equivalent of a DOS command window running Linux, with all the tools like grep built in. If you want more information about grep, just type info grep. If you'd like to be able to have a "bash prompt here" facility, see this page.

Later: someone pointed out that Windows now has findstr already installed. I've been using cygwin and grep for awhile now so I wasn't looking for this, and didn't know it had been added (or when). But it appears to be quite powerful and includes regular expressions -- and has the benefit of already being on your machine. I use cygwin to solve many other problems, so it has far more value than just grep.

With cygwin installed, go to the root of the Java source code directory (after you've installed the lastest version of JDK 5.0 from java.sun.com, of course). Here's the grep command that I used:

grep -R -n -B 3 -A 10 --include="*.java" "([A-Z]\[\])" .

The -R flag tells grep to recurse through all subdirectories. The --include="*.java" flag tells it to only include Java files in the search. -n says to print line numbers. -B 3 says to print three lines before the match, and -A 10 says to print 10 lines after the match. And the regular expression itself says to find everything that looks like an array cast to a generic type, for example '(T[])'. You can see that GNU grep is a powerful tool for searching the Java sources for example code.

The findstr equivalent is:

findstr /N /S /R "([A-Z]\[\])" *.java

Unfortunately, you do not get the benefit of being able to print lines before and after the match, as you do with GNU grep. (It is possible that someone has ported GNU grep to Windows by itself, so that you don't have to install all of Cygwin).

0 Comments:

Post a Comment

<< Home