57

How do I recursively grep files within a given folders except a couple file types?

For example, I'm looking for a string within my workspace folder but it ends up searching inside sql files and generates serialized strings.

So in this case, I'd like to grep the workspace folder except sql files.

I'm preferably looking for a one-liner if possible.

1
  • 6
    Be aware that Linux and Unix and unix-a-likes don't really have "file types" in the way you seem to want. It's only by convention that file names have a ".c" or ".txt" or ".sql" suffix - those suffixes aren't even Windows-style "extensions", much less indicators that SQL or text or C source code live inside the files.
    – user732
    Commented Feb 8, 2012 at 23:35

2 Answers 2

77

If you have GNU grep you can use the --exclude=GLOB option, like

grep -r --exclude='*.sql' pattern dir/
2
11

This will do that for you and exclude .sql and .txt files:

find /some/dir -type f ! -name '*\.sql' ! -name '*.txt' -print0 | xargs -0 grep 'foobar'

However it sounds like ack would be a far better tool for what you're trying to do:

ack -a --nosql 'foobar' /some/dir
3
  • Sorry, I didn't see the 'ack' part and put it in my answer, which is now deleted.
    – Chance
    Commented Feb 9, 2012 at 15:16
  • Another user notes that ack - a --nobinary includes binary files Commented Nov 15, 2012 at 18:23
  • The backslash in the filename pattern is not needed.
    – Kusalananda
    Commented May 15, 2018 at 17:09

You must log in to answer this question.

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