find
是 Linux 系统中最强大且常用的文件搜索工具之一,它可以根据各种条件(如文件名、类型、大小、修改时间等)在目录树中查找文件,并能对找到的文件执行操作。
find [路径] [选项] [表达式]
find /path -name "filename" # 精确匹配文件名
find /path -iname "filename" # 不区分大小写
find /path -name "*.txt" # 通配符查找
find /path -regex ".*\.txt$" # 使用正则表达式
find /path -type f # 查找普通文件
find /path -type d # 查找目录
find /path -type l # 查找符号链接
find /path -type b # 查找块设备文件
find /path -type c # 查找字符设备文件
find /path -type p # 查找命名管道(FIFO)
find /path -type s # 查找套接字(socket)
find /path -size +10M # 大于10MB的文件
find /path -size -1G # 小于1GB的文件
find /path -size 1024c # 等于1024字节的文件
单位说明:
- b
:512字节块(默认)
- c
:字节
- w
:双字节字
- k
:KB
- M
:MB
- G
:GB
find /path -mtime -7 # 7天内修改过的文件
find /path -mtime +30 # 30天前修改过的文件
find /path -atime +60 # 60天前访问过的文件
find /path -cmin -10 # 10分钟内状态改变的文件
时间选项:
- -atime
:访问时间(天)
- -mtime
:修改时间(天)
- -ctime
:状态改变时间(天)
- -amin
:访问时间(分钟)
- -mmin
:修改时间(分钟)
- -cmin
:状态改变时间(分钟)
find /path -perm 644 # 权限精确匹配644的文件
find /path -perm -644 # 权限包含644的文件
find /path -perm /u=r # 用户有读权限的文件
find /path -user username # 属于某用户的文件
find /path -group groupname # 属于某用户组的文件
find /path -nouser # 没有有效用户的文件
find /path -nogroup # 没有有效用户组的文件
find /path \( -name "*.txt" -o -name "*.pdf" \) # 查找txt或pdf文件
find /path -name "*.log" -a -mtime +30 # 查找30天前的log文件
find /path ! -name "*.bak" # 排除bak文件
逻辑运算符:
- -a
:与(AND,默认)
- -o
:或(OR)
- !
:非(NOT)
find /path -name "*.txt" -print
find /path -name "*.tmp" -exec rm {} \; # 删除所有tmp文件
find /path -name "*.jpg" -exec chmod 644 {} \; # 修改jpg文件权限
find /path -type f -empty -delete # 删除空文件
说明:
- {}
:代表find找到的文件名
- \;
:表示命令结束(注意空格和分号)
find /path -name "*.log" -ls # 显示详细文件信息
find /path -name "*.txt" -ok rm {} \; # 交互式删除(每次询问)
find /path -printf "%p %s\n" # 自定义输出格式
find /path -maxdepth 2 -name "*.conf" # 最多查找2层目录
find /path -mindepth 3 -name "*.sh" # 从第3层目录开始查找
find /path -name "*.log" -exec gzip {} \;
find /path -type f | wc -l
find /path -type f -printf "%s %p\n" | sort -n
find /var/log -name "*.log" -mtime +7 -exec rm {} \;
find . -name "*.php" -exec php -l {} \;
find / -type f -size +100M -exec ls -lh {} \;
find /path -empty
find /etc -name "*.conf" -exec cp {} {}.bak \;
find命令功能非常强大,上述只是常用功能的介绍。通过组合不同的选项和表达式,可以满足各种复杂的文件查找需求。