find命令

写在前面:总结find常见用法
1.忽略大小写 -i
find /home -iname "*.txt"
当前目录及子目录下查找所有以.txt和.pdf结尾的文件
2.find . -name "*.txt" -o -name "*.pdf"
3.匹配文件路径 -path
find /usr/ -path "*local*"
4.基于正则表达式匹配文件路径 -regex
find . -regex ".*(.txt|.pdf)$"
5.否定参数!
找出/home下不是以.txt结尾的文件
find /home ! -name "*.txt"
6.根据文件类型进行搜索 -type
find . -type 类型参数
f 普通文件 d 目录 c 字符设备 b 块设备
7.基于目录深度搜索 -maxdepth -mindepth
向下最大深度限制为3
find . -maxdepth 3 -type f
搜索出深度距离当前目录至少2个子目录的所有文件
find . -mindepth 2 -type f
8.根据文件时间戳进行搜索
find . -type f 时间戳
UNIX/Linux文件系统每个文件都有三种时间戳:
访问时间(-atime/天,-amin/分钟)access:用户最近一次访问时间。
修改时间(-mtime/天,-mmin/分钟)modify:文件最后一次修改时间。
变化时间(-ctime/天,-cmin/分钟)change:文件数据元(例如权限等)最后一次修改时间。
搜索最近七天内被访问过的所有文件
find . -type f -atime -7
搜索恰好在七天前被访问过的所有文件
find . -type f -atime 7
搜索超过七天内被访问过的所有文件
find . -type f -atime +7
搜索超过七天内被访问过的所有文件
find . -type f -atime +7
搜索访问时间超过10分钟的所有文件
find . -type f -amin +10
找出比file.log修改时间更长的所有文件
find . -type f -newer file.log
根据文件大小进行匹配 -size
find . -type f -size 文件大小单元
搜索大于10KB的文件
find . -type f -size +10k
搜索小于10KB的文件
find . -type f -size -10k
根据文件权限/所有权进行匹配 -perm -user
find . -type f -perm 777
find . -type f -name "*.php" ! -perm 644
find . -type f -user tom
find . -type f -group sunk
9.借助-exec选项与其他命令结合使用
找出当前目录下所有root的文件,并把所有权更改为用户tom
find .-type f -user root -exec chown tom {} ;
找出自己家目录下所有的.txt文件并删除
find $HOME/. -name "*.txt" -ok rm {} ;
上例中,-ok和-exec行为一样,不过它会给出提示,是否执行相应的操作。
查找当前目录下所有.txt文件并把他们拼接起来写入到all.txt文件中
find . -type f -name "*.txt" -exec cat {} ;> all.txt
将30天前的.log文件移动到old目录中
find . -type f -mtime +30 -name "*.log" -exec cp {} old ;
找出当前目录下所有.txt文件并以“File:文件名”的形式打印出来
find . -type f -name "*.txt" -exec printf "File: %s " {} ;

exec与xargs区别
区别描述: 两者都是对符合条件的文件执行所给的Linux 命令,而不询问用户是否需
要执行该命令。
-exec:{}表示命令的参数即为所找到的文件,以;表示command命令的结束。是转义符,
因为分号在命令中还有它用途,所以就用一个来限定表示这是一个分号而不是表示其它意思。

-ok: 和 -exec 的作用相同,格式也一样,只不过以一种更为安全的模式来执行该参数
所给出的shell给出的这个命令之前,都会给出提示,让用户来确定是否执行。

xargs 要结合管道来完成
格式:find [option] express |xargs command
用一个实例来看看exec和xargs是如何传参数的:
$find test/ -type f
test/myfile.name
test/files/role_file
test/files/install_file


$find test/ -type f |xargs echo
test/myfile.name test/files/role_file test/files/install_file


$find test/ -type f -exec echo {} ;
test/myfile.name
test/files/role_file
test/files/install_file
很明显,exec是对每个找到的文件执行一次命令,除非这单个的文件名超过了几k,否则不
会出现命令行超长出报错的问题。

而xargs是把所有找到的文件名一股脑的转给命令。当文件很多时,这些文件名组合成的命
令行参数很容易超长,导致命令出错。

另外, find | xargs 这种组合在处理有空格字符的文件名时也会出错,因为这时执行的命令
已经不知道哪些是分割符、哪些是文件名中的空格! 而用exec则不会有这个问题。


比如做个演示:

$touch test/'test zzh'

$find test/ -name *zzh
test/test zzh

$find test/ -name *zzh |xargs rm
rm: cannot remove `test/test': No such file or directory
rm: cannot remove `zzh': No such file or directory

$find test/ -name *zzh -exec rm {} ;

相比之下,也不难看出各自的缺点
1、exec 每处理一个文件或者目录,它都需要启动一次命令,效率不好; 
2、exec 格式麻烦,必须用 {} 做文件的代位符,必须用 ; 作为命令的结束符,书写不便。
3、xargs 不能操作文件名有空格的文件;
综上,如果要使用的命令支持一次处理多个文件,并且也知道这些文件里没有带空格的文件,
那么使用 xargs比较方便; 否则,就要用 exec了。

原文地址:https://www.cnblogs.com/move-on-change/p/9515777.html