Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I wish to search for keyword "test", in all files which are of type "*.spec.in" in the current directory recursively This doesn't work:

grep -rn "test" ./*.spec.in

How do I do this?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

If you think about what this does, this can't work. The -r flag means grep will expect a directory as it's file source, but your glob will match files (or nothing). This is a mismatch.

You can do this a few ways.

The "textbook" way, usable on any UNIX (any shell really) is to separate responsibility. Use find to do the recursion, and separately do grep. Lets find all the files that match, and hand those to grep

find . -type f -name '*.spec.in' | xargs grep -n "test"

find, starting from here, files, with name matching '*.spec.in', passing that stream off to xargs, which will turn the stream into command line args for your grep.

If you have no spaces in filenames, this is fine. But if you do, or if you use this to make changes on disk, you probably want this a bit tighter. There are hacks where you can mess with filenames to harm important files on disk, so you want to be very careful for filename hacks. For security, or spaces in names, you can tell find and xargs to communicate more tightly. See -print0, -0 below.

find . -type f -name '*.spec.in' -print0 | xargs  -0 something_destructive_like_rm

On newer shells, such as zsh or newer versions of bash you can use recursive globs, which use a special ** syntax. They'll recursively match a file pattern.

shopt -s globstar # needed for bash, not for zsh
grep "test" ./**/*.spec.in
share|improve this answer
    
Thanks! The recursive glob solution worked for me. –  Bruce Aug 28 '13 at 21:37
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.