grep --exclude不排除我的文件


8

我正在目录中搜索特定的字符串(以查看该字符串存在的位置和文件中的所有实例)。但是,我想从搜索中排除一个特定的文件。

这是正在发生的事情-

$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

这是我想要的输出-

./new_folder/good_file:searchstring

6
如果您更改--exclude="old_folder/useless_file"为干脆--exclude=useless_file会遇到相同的问题?(我对手册页的阅读表明,该模式--exclude应仅是基本名称,不包括路径。)
通配符

Answers:


11

--exclude选项采用与文件名而不是目录或完整路径匹配的glob:

  --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.

因此,您可以执行以下操作:

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

或者,要排除该目录中的所有文件:

$ grep -r --exclude-dir="old_folder" searchstring 
new_folder/good_file:searchstring
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.