Grep –exclude Not Excluding File – How to Fix

grepsearch

I am searching a dir for a particular string (to see all instances of where the string is present and in which files). However, I want to exclude one particular file from being searched.

Here's what is happening-

$echo "searchstring" > ./old_folder/useless_file
$echo "searchstring" > ./new_folder/good_file
$grep -r --exclude="old_folder/useless_file" searchstring *
./old_folder/useless_file:searchstring
./new_folder/good_file:searchstring

Here is the output I want-

./new_folder/good_file:searchstring

Best Answer

The --exclude option takes globs that are matched against file names, not directories or full paths:

  --exclude=GLOB
          Skip   files  whose  base  name  matches  GLOB  (using  wildcard
          matching).  A file-name  glob  can  use  *,  ?,  and  [...]   as
          wildcards,  and  \  to  quote  a wildcard or backslash character
          literally.

So, you could do:

$ grep -r --exclude="*useless_file*" searchstring 
new_folder/good_file:searchstring

Or, to exclude all files in that directory:

$ grep -r --exclude-dir="old_folder" searchstring 
new_folder/good_file:searchstring
Related Question