用 grep 查找的时候,如果想在查找范围中排除掉某个目录和文件,怎么做?
很简单,用 --exclude=xxxx 或者 --exclude-dir=xxxx(用于目录)
举例子
$ grep 1111 -r .
./a.txt:1111
./b.txt:1111111
./c.txt:11111222221
假如要排除掉文件 a.txt
$ grep 1111 --exclude=a.txt -r .
./b.txt:1111111
./c.txt:11111222221
假如要排除掉当前目录
$ grep 1111 --exclude-dir=./ -rn .
结果是啥也没有
需要注意的是:
$ grep 1111 --exclude=./a.txt -rn .
./a.txt:1:1111
./b.txt:1:1111111
./c.txt:1:11111222221
这样写不起作用
一定要写成
$ grep 1111 --exclude=a.txt -r .
但是,如果当前目录下还有子目录,我们想排除子目录中的某个文件
比如
$ find . -type f
./a.txt
./b.txt
./c.txt
./ss/s.txt // 假设要排除这个
先试试用 --exclude 选项
$ grep 1111 --exclude="ss/s.txt" -rn .
./a.txt:1:1111
./b.txt:1:1111111
./c.txt:1:11111222221
./ss/s.txt:1:11116666
$ grep 1111 --exclude="./ss/s.txt" -rn .
./a.txt:1:1111
./b.txt:1:1111111
./c.txt:1:11111222221
./ss/s.txt:1:11116666
learner@ubt:/mnt/hgfs/vm_share/grep_test$
不灵了。
这可怎么办呢?
各种尝试,都不行,最后试出了这样的方法:
$ find . -type f ! -path "./ss/s.txt" | xargs grep '1111'
./a.txt:1111
./b.txt:1111111
./c.txt:11111222221
解释一下:
find . -type f
表示查找当前目录下的所有文件,含子目录
-path "./ss/s.txt"
表示用 find 查找的时候要排除掉的文件(可以用正则表达式) “./ss/s.txt”
xargs
表示把 find 命令的结果作为参数传递给 grep
【End】