使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
当前回答
path-prune方法还可以处理路径中的通配符。下面是一个find语句,它将查找服务于多个git存储库的git服务器的目录,而不包括git内部目录:
find . -type d \
-not \( -path */objects -prune \) \
-not \( -path */branches -prune \) \
-not \( -path */refs -prune \) \
-not \( -path */logs -prune \) \
-not \( -path */.git -prune \) \
-not \( -path */info -prune \) \
-not \( -path */hooks -prune \)
其他回答
这适合我在Mac上使用:
find . -name *.php -or -path "./vendor" -prune -or -path "./app/cache" -prune
它将排除带有php后缀的搜索名称的供应商和app/cache-dir。
-prune绝对有效,并且是最好的答案,因为它可以防止下降到要排除的目录中-not-path仍然搜索排除的目录,它只是不打印结果,如果排除的目录已装入网络卷或您没有权限,这可能是一个问题。
棘手的是,find对参数的顺序非常讲究,所以如果你不能正确地获取它们,你的命令可能无法正常工作。论点的顺序一般如下:
find {path} {options} {action}
{path}:首先放置所有与路径相关的参数,如-路径'/dir1'-修剪-o
{options}:将-name、-iname等作为此组中的最后一个选项时,我最成功。例如-type f-iname“*.js”
{action}:使用-prine时需要添加-print
下面是一个工作示例:
# setup test
mkdir dir1 dir2 dir3
touch dir1/file.txt; touch dir1/file.js
touch dir2/file.txt; touch dir2/file.js
touch dir3/file.txt; touch dir3/file.js
# search for *.js, exclude dir1
find . -path './dir1' -prune -o -type f -iname '*.js' -print
# search for *.js, exclude dir1 and dir2
find . \( -path './dir1' -o -path './dir2' \) -prune -o -type f -iname '*.js' -print
我在C源文件exclude*.o和exclude*.swp以及exclude(非常规文件)和exclude-dir输出中找到了函数名:
find . \( ! -path "./output/*" \) -a \( -type f \) -a \( ! -name '*.o' \) -a \( ! -name '*.swp' \) | xargs grep -n soc_attach
有很多好的答案,我只是花了一些时间来理解命令的每个元素是什么以及背后的逻辑。
find . -path ./misc -prune -o -name '*.txt' -print
find将开始查找当前目录中的文件和目录,因此查找。。
-o选项代表逻辑OR,并将命令的两部分分开:
[ -path ./misc -prune ] OR [ -name '*.txt' -print ]
不是的任何目录或文件/misc目录不会通过第一个测试路径/其他。但他们将根据第二个表达式进行测试。如果它们的名称与模式*.txt相对应,则会因为-print选项而被打印。
当find到达时/misc目录,此目录仅满足第一个表达式。因此,将对其应用-prune选项。它告诉find命令不要浏览该目录。中的任何文件或目录/find甚至不会探索misc,不会针对表达式的第二部分进行测试,也不会打印。
我想知道目录的数量,文件的大小(仅为当前目录的MB),而这段代码正是我想要的:-)
来源
- ... 2791037 Jun 2 2011 foo.jpg
- ... 1284734651 Mär 10 16:16 foo.tar.gz
- ... 0 Mär 10 15:28 foo.txt
d ... 4096 Mär 3 17:12 HE
d ... 4096 Mär 3 17:21 KU
d ... 4096 Mär 3 17:17 LE
d ... 0 Mär 3 17:14 NO
d ... 0 Mär 3 17:15 SE
d ... 0 Mär 3 17:13 SP
d ... 0 Mär 3 17:14 TE
d ... 0 Mär 3 19:20 UN
代码
format="%s%'12d\n"
find . -type d -not -path "./*/*" | wc -l | awk -v fmt=$format '{printf fmt, " Anzahl Ordner = ", $1-1}'
find . -type f -not -path "./*/*" | wc -l | awk -v fmt=$format '{printf fmt, " Anzahl Dateien = ", $1}'
du . -hmS --max-depth=0 | awk -v fmt=$format '{printf fmt, " Groesse (MB) = ", $1}'
注意:awk需要额外的format=“%s%12d\n”来格式化数字。
结果
Anzahl Ordner = 8
Anzahl Dateien = 3
Groesse (MB) = 1.228