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.

  • 5
    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. – Bruce Ediger Feb 8 '12 at 23:35

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

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

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
  • Sorry, I didn't see the 'ack' part and put it in my answer, which is now deleted. – Chance Feb 9 '12 at 15:16
  • Another user notes that ack - a --nobinary includes binary files – Michael Mrozek Nov 15 '12 at 18:23
  • The backslash in the filename pattern is not needed. – Kusalananda May 15 '18 at 17:09

protected by ilkkachu May 21 '18 at 11:23

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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