find中对结果执行其他命令
删除文件
使用参数-delete,不需要使用-exec rm -f {} \;,因为-exec会创建子shell来执行rm -f。
find -exec命令中[+]与[\;]的区别
在find -exec命令中{}是文件的占位符,在+模式下会扩展为文件列表。
Bash
# === 使用 \; 执行3次ls命令
find . -name "*.txt" -exec ls -l {} \;
# 相当于:ls -l ./file1.txt
# ls -l ./file2.txt
# ls -l ./file3.txt
# === 使用 + 执行1次ls命令,将所有匹配的文件一次性传递给命令
find . -name "*.txt" -exec ls -l {} +
# 相当于:ls -l ./file1.txt ./file2.txt ./file3.txtsh文件中-exec后面要使用函数时,需要先导出。
比如:在sh文件中定义了函数subDirectoryCheck ,但在执行sh中的行
Bash
find /data/www/rpFiles -maxdepth 1 -mindepth 1 -type d -exec subDirectoryCheck {} \;报错:find: ‘subDirectoryCheck’: No such file or directory
解决方法:
- 将函数为独立的文件,添加执行权限,再在
-exec中调用 - 先使用
export -f subDirectoryCheck导出函数,使其在子shell中可用;再在-exec中使用bash -c 'subDirectoryCheck "$0"'
完整示例:
Bash
export -f subDirectoryCheck
find /data/www/rpFiles -maxdepth 1 -mindepth 1 -type d -exec bash -c 'subDirectoryCheck "$0"' {} \;与xargs配合
somecommand |xargs -item command
xargs命令在Linux中是一个非常实用的工具,它主要用于将标准输入数据转换为命令行参数。xargs能够读取stdin的输入数据,将其转换成特定命令的参数形式,然后执行该命令。
xargs 默认的命令是 echo,这意味着通过管道传递给 xargs 的输入将会包含换行和空白,不过通过 xargs 的处理,换行和空白将被空格取代。
Bash
# 查找当前目录下所有的.txt文件,并删除它们
find . -type f -name "*.txt" | xargs rm
# 查找当前目录下所有的.jpg文件,并将它们压缩成一个tar.gz文件
find . -type f -name "*.jpg" | xargs tar -czvf images.tar.gz
# 使用自定义分隔符
echo "splitXsplitXsplitXsplit" | xargs -dX
split split split split带#为命令,无#为输出:
Bash
# cat test.txt
a b c d e f g
h i j k l m n
o p q
r s t
u v w x y z
# cat test.txt | xargs
a b c d e f g h i j k l m n o p q r s t u v w x y z
# cat test.txt | xargs -n3
a b c
d e f
g h i
j k l
m n o
p q r
s t u
v w x
y z
# echo "nameXnameXnameXname" | xargs -dX -n2
name name
name name按权限搜索文件
find [查找路径] -perm [权限模式]
- 精确查找,比如:文件权限为644(
rw-r--r--)命令为find . -type f -perm 644 - 所有位的包含查找(ugo都包含),比如:u/g/o都有执行权限的文件命令为
find . -type f -perm -111 - 任意位的包含查找(ugo任一个包含就满足),比如:u/g/o任一有执行权限的文件命令为
find . -type f -perm /111
背景:在Linux文件权限中,每个权限由3位/组的数字(用户、组、其他)表示。下图在ll中显示为rwx-r-xr-x

搜索不是nginx用户的文件
find . -type f -not -user nginx
发表回复