Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude a directory in a recursive search using grep?

Tags:

How to do a recursive search using grep while excluding a particular directory ?

Background : I have a large directory consisting of log files which I would like to eliminate in the search. The easiest way is to move the log folder. Unfortunately I cannot do that, as the project mandates the location.

Any idea how to do it ?

like image 871
Kiran Avatar asked Nov 18 '11 15:11

Kiran


People also ask

How do I use grep to search recursively?

To recursively search for a pattern, invoke grep with the -r option (or --recursive ). When this option is used grep will search through all files in the specified directory, skipping the symlinks that are encountered recursively.

How do I exclude multiple items in grep?

Specify Multiple Patterns. The -e flag allows us to specify multiple patterns through repeated use. We can exclude various patterns using the -v flag and repetition of the -e flag: $ grep -ivw -e 'the' -e 'every' /tmp/baeldung-grep Time for some thrillin' heroics.

Can grep search directories?

The grep command is a useful Linux command for performing file content search. It also enables us to recursively search through a specific directory, to find all files matching a given pattern. Let's look at the simplest method we can use to grep the word “Baeldung” that's included in both .


2 Answers

are you looking for this?

from grep man page:

--exclude-dir=DIR
            Exclude directories matching the pattern DIR from recursive searches.
like image 67
Kent Avatar answered Oct 18 '22 21:10

Kent


As an alternate, if you can use find in your search, it may also be useful:

find [directory] -name "*.log" -prune -o -type f -print|grep ...
The [directory] can actually be the current directory if you want (just a . will do).

The next part, -name "*.log" -prune is all together. It searches for filenames with the pattern *.log and will strip them OUT of your results.

Next is -o (for "or")

Then, -type f -print which says "print (to stdout) any type that is a file."

Those results should include every file (no directories are returned) found in [directory] except those that end in .log. Then you can grep the results as you need.

like image 40
OnlineCop Avatar answered Oct 18 '22 21:10

OnlineCop