Searching file contents with grep

I find OSX’s search tool Spotlight to be somewhat wanting. Sometimes I want to find something quickly in my coding folder, and what better way to do that but on the command line? But how? Is the best way using find, or a combination of find and grep? The find command is normally used for finding files, and you can find a large collection of different examples here. Grep on the other hand searches for lines in a file that match a pattern. grep gets its name from the ed (editor) command g/regular-expression/p.

In many cases I want to search the entire directory hierarchy, recursively. The following command uses find to find files, and grep to search for a pattern.

find . -type f -exec grep -l 'GOTO' {} \;

This basically searches all files in all subdirectories of the current directory (“.”) for the pattern “GOTO“, and prints any results. Here is a sample output:

./closed_loop.for
./tictactoe/a1w18.for
./tictactoe/ttt.f95
./tictactoe/tictactoe.for
./legacy/overcommentF.for
./closed_loop2.for
./ttt.f95
./calc.for
./gotoWITHloop.f95
./loop_goto.for

This is useful, but it is somewhat of a handful to remember. A easier way is just using grep, recursively.

grep -rl GOTO .

The “-rl” implies recursively output “files-with-matches”. It produces the same output as the combined find/grep command above. To search for files with either of one of two patterns, one can use the “-E” option, with the “or” symbol, |. The code below will search for either goto or GOTO.

grep -rl -E 'goto|GOTO' .

This can also be done using the “-i” option to ignore case.

grep -irl goto .

To print out the line number of the pattern being searched for, use the “-n” option. For example:

grep -nr GOTO .

Here is a sample output:

./tictactoe/a1w18.for:47:      IF (TURN .EQ. 1) GOTO 16
./tictactoe/a1w18.for:50:      IF (OVER) GOTO 30
./tictactoe/a1w18.for:54:      GOTO 14
./tictactoe/a1w18.for:56:      IF (OVER) GOTO 30
./tictactoe/a1w18.for:57:      GOTO 10

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.