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 *

Here is the output I want-

  • 6
    If you change --exclude="old_folder/useless_file" to simply --exclude=useless_file do you get the same problem? (My reading of the man page suggests the pattern to --exclude should be the basename only, not including the path.) – Wildcard Mar 30 '16 at 15:51

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

          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

So, you could do:

$ grep -r --exclude="*useless_file*" searchstring 

Or, to exclude all files in that directory:

$ grep -r --exclude-dir="old_folder" searchstring 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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