tags:

views:

496

answers:

8

Right now I do this a lot:

find * | grep py$ | xargs grep foo

I recall there is some util that does this with way less typing, but which?

UPDATE: I prefer to use the Bash shell if possible.

+4  A: 

You may find your shell helps you. For instance, in zsh, you can do

grep foo **/*.py

provided the number of .py files doesn't exceed the maximum number of arguments allowed for a command (64k?). Note you can qualify the file globbing e.g.

grep foo **/*.py(mh-5)

which will give you everything modified in the last 5 hours.

Brian Agnew
not any better, almost the same # of keystrokes;
Jay Stevens
Hence the zsh globbing
Brian Agnew
+1  A: 
grep -r --include='*.py' foo *
chaos
That's an odd definition of the word "less"
skaffman
Yeah. Less chaining feels like less worry to me, but OP didn't ask for less worry, he asked for less typing. Edited to something actually shorter. Slightly.
chaos
+1  A: 
find . -name "*.py" -exec grep -H foo '{}' ';'
Pierre
Tip: end your exec expression with a '+' instead of ';', which will make find send all matching files to a single grep process instead of forking off a new one for each matching file. Much more efficient that way.
Lars Haugseth
+2  A: 

zsh has recursive globbing, so you can do

grep foo **/*.py

Look ma, no find :)

UPDATE: Oh, also if you do something a lot it doesn't hurt to alias or write a function for it of course

Eric Wendelin
Given zsh's ability to do this, I barely have to mess with find's arcane syntax
Brian Agnew
+2  A: 

It's called grep *wink* :-)

All py in current directory

grep -R foo *.py

All files in current and any sub-directory

grep -R foo .
jitter
+1: -R is standard on most UNIX commands to also scan subdirectories recursively.
R. Bemrose
Don't you need to quote or escape your globbing ? Otherwise the shell will expand this in the current directory ?
Brian Agnew
You are right about that
jitter
+13  A: 

I love ack:

Which would you rather type?

$ grep pattern $(find . -type f | grep -v '\.svn')

$ ack pattern

dfa
ack --python foo is sweet!
kotlinski
ack is the bees knees.
seth
+3  A: 

Have you tried ack.

Aditya Sehgal
yeah, ack is a great replacement for grep (at least for programmers)
dfa
A: 

I use something very much like your find/grep pair a lot, although with even more conditions -- excluding files in .svn directories, for example. I do this so much I just made scripts around these invocations, so I can call "src-grep ..." and have it do basically what you're doing here. (Then I added an optional extension for a number of context lines to pass to the grep -C flag, if supplied, and a separate version to grep the results for definition statements.)

This is more useful and faster than recursive grep for me.

khedron