写于:2015-05-10 最近一次更新:2019-05-25
Intent:
同时指定多个待查找的目录
Oneway:
find ./build ./device ./vendor -type f | xargs -I {} grep REQUIRED_MODULES -m 1 -l {}
这条命令表示在build,device,vendor这三个目录下查找文件,找出文件内容包含 REQUIRED_MODULES 关键词的文件
Intent:
排除某一个具体目录如 test ,不对这个 test 目录进行查找操作
排除所有名字为 test 的目录,不对这类目录进行查找操作
Oneway:
find /tmp -path '/tmp/test' -prune -o -print
find /tmp -name 'test' -prune -o -print
解释: 一般, -print 是默认执行的,不需要显式指定,
仅当指定 -prune 时 -print 才不会默认执行,要想得到打印流必须显示指定;
也即指定参数 -prune 时必须同时指定 -print 才能得到结果的打印流
-o 相当于 shell 的 || 表示或,这句命令的含义等同于下面这段伪码
if -path==/tmp/test then
-prune
else
-print
查找目录时,-path 目录名称的最后面一定不要带/
若查找目录时使用的是绝对路径则-path也要使用绝对路径;
若查找目录时使用的是相对路径则-path也要使用相对路径,例如
find ./ -path './.git' -prune -o -type f -print | xargs -I {} sed -i 's/old/new/g' {}
排除多个目录如 test01,test02,test03 ,不对 test01,test02,test03 这三个目录进行查找操作,命令如下
find /tmp -path '/tmp/test01' -prune \
-o -path '/tmp/test02' -prune \
-o -path '/tmp/test03' -prune \
-o -print
以后缀名为依据,排除某一种类型的文件,如排除目录下所有以 html 结尾的文件
find /tmp -type f ! -name '*.html'
以后缀名为依据,排除多种类型的文件,如排除目录下所有以 .bak,.mp3,.avi 结尾的文件
find /tmp -type f ! -regex '*.doc \| *.mp3 \| *.avi'
Trouble:
-name参数使用错误
在使用命令 find ./ -name *.zip 时出现下面的错误提示
find: paths must precede expression: 正则表达式(匹配).zip
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
Oneway:
因为使用了 find 的 -name 参数,所以首先 man find 找到 -name 的参数说明,看到这样一句话
Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell.
就是说 -name 后的表达式要用引号扩起来,防止表达式被 shell 解释后再传递给 find 命令
(不加引号的话,*号会被shell解释成当前目录下所有文件的名称,而不会作为正则表达式传给 find )
正确做法是在使用 -name 参数时就给其后的表达式加上引号,建议使用单引号
Intent:
find 的参数 -exec必须与 \; 或者 \+ 搭配使用,但是这两种搭配有什么区别呢?
Oneway:
\; 表示每传入一个参数 -exec 后的命令就会执行一次,即 -exec 后的命令会执行多次
\+ 表示所有参数会一并传给 -exec 后的命令,且只执行一次,需要-exec后的命令支持处理多个参数
下面的例子可以很好的说明 \; 与 \+ 的区别
mkdir test && cd test
cat > myecho << EOF
#!/bin/bash
echo "参数有:\$@"
echo "参数总个数:\$#"
echo
EOF
chmod u+x myecho
mkdir files && cd files
touch file01 file02 file03
find * -exec ../myecho {} \;
参数有:file01
参数总个数:1
参数有:file02
参数总个数:1
参数有:file03
参数总个数:1
find * -exec ../myecho {} \+
参数有:file01 file02 file03
参数总个数:3
但是,很少使用-exec参数,通常是让find结合xargs来执行命令
|