bash函数grep--exclude dir不工作
我在.bashrc中定义了以下函数,但由于某种原因--exclude dir选项并不排除.git目录。有人能看出我做错了什么吗?如果有帮助的话,我正在使用Ubuntu 13.10bash函数grep--exclude dir不工作,bash,grep,find,Bash,Grep,Find,我在.bashrc中定义了以下函数,但由于某种原因--exclude dir选项并不排除.git目录。有人能看出我做错了什么吗?如果有帮助的话,我正在使用Ubuntu 13.10 function fif # find in files { pattern=${1?" Usage: fif <word_pattern> [files pattern]"}; files=${2:+"-iname \"$2\""}; grep "$pattern" --color -n
function fif # find in files
{
pattern=${1?" Usage: fif <word_pattern> [files pattern]"};
files=${2:+"-iname \"$2\""};
grep "$pattern" --color -n -H -s $(find . $files -type f) --exclude-dir=.git --exclude="*.min.*"
return 0;
}
函数fif#在文件中查找
{
模式=${1?“用法:fif[文件模式]”};
files=${2:+“-iname\“$2\”“};
grep“$pattern”-color-n-H-s$(find.$files-typef)--exclude dir=.git--exclude=“*.min.*”
返回0;
}
在您的系统上执行手动grep
,然后查看您的版本。您的grep版本可能无法使用--排除目录
您最好使用find
查找所需文件,然后使用grep
解析它们:
$ find . -name '.git' -type d -prune \
-o -name "*.min.*" -prune \
-o -type f -exec grep --color -n -H {} "$pattern" \;
我不喜欢递归的grep
。它的语法已经变得臃肿,而且真的没有必要了。我们有一个非常好的工具来查找符合特定条件的文件,谢谢
在find
程序中,-o
分隔出各种子句。如果一个文件没有被前一个-prune
子句过滤掉,它将被传递到下一个。删除所有.git
目录和所有*.min.
文件后,将结果传递给-exec
子句,该子句对该文件执行grep命令
有些人喜欢这样:
$ find . -name '.git' -type d -prune \
-o -name "*.min.*" -prune \
-o -type f -print0 | xargs -0 grep --color -n -H "$pattern"
-print0
打印出所有找到的文件,文件之间用空字符分隔。xargs-0
将读入该文件列表并将其传递给grep
命令。-0
告诉xargs
文件名以NULL分隔,而不是以空格分隔。一些xarg
将采用--null
而不是-0
参数 指定要排除的目录时,请确保不包含尾随斜杠。例如:
这样做:
$ grep -r --exclude-dir=node_modules firebase .
不是这个:
$ grep -r --exclude-dir=node_modules/ firebase .
(这个答案不适用于OP,但可能有助于发现
--exclude dir
不起作用的其他人--它对我起作用。)--exclude dir
选项仅在GNU grep(>=2.5.2)的最新版本中可用。你可能会发现有用的,嗯,真的。我有2.15分。现在,我无法理解为什么--exclude dir的信息包含在手册页中。棘手的问题。--exclude dir
是否应该与-r
(递归)一起使用?绝对路径似乎也是一个禁忌。我从根目录中搜索,希望避免/dev
,/proc
,/sys
,等等。--exclude dir=/dev
不起作用,而--exclude dir=dev
按预期工作。哇,太不直观了。谢谢你的支持。这是因为--exclude dir只匹配基名称。这意味着引用嵌套文件夹也不会起作用,例如--exclude dir=mydir/node_模块应该是--exclude dir=node_模块。请看这里: