Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. 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

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.

share|improve this question
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
up vote 24 down vote accepted

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

grep -r --exclude='*.sql' pattern dir/
share|improve this answer
How to exclude a single file? – Nayeem Oct 8 '15 at 11:56

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
share|improve this answer
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

In bash, I've had success with the following short, quick command when wanting to exclude just one file from a grep:

grep <string> *[!EXCLUDEFILE.EXT].EXT
share|improve this answer


ls | grep -v "ext$"

ext -> being an extention that you specify

The flag -v is to exclude. The $ is the end of line, it's a regex symbol.

share|improve this answer
This doesn't answer the question: the OP is trying to run grep on files, not get a list of files. ls should never be a starting point for any script that deals with lists of files. – jw013 Feb 9 '12 at 7:00
It can be applied the same way to files, I think it'd be fastest and easiest to test and see result if I gave the command like that. – krack krackerz Feb 10 '12 at 4:37

Your Answer


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.