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 ?
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.
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.
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 .
are you looking for this?
from grep man page:
--exclude-dir=DIR
Exclude directories matching the pattern DIR from recursive searches.
As an alternate, if you can use find
in your search, it may also be useful:
The find [directory] -name "*.log" -prune -o -type f -print|grep ...
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With