Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

grep -rn "test" ./*

How do I do this?

share|improve this question
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 '*' | xargs grep -n "test"

find, starting from here, files, with name matching '*', 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 '*' -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" ./**/*
share|improve this answer
Thanks! The recursive glob solution worked for me. – Bruce Aug 28 '13 at 21:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .