Appearance
文件查找
find 命令
基本用法
bash
#!/bin/bash
# 查找文件
find /path/to/directory -name "filename"按名称查找
bash
#!/bin/bash
# 按名称查找
find /path/to/directory -name "filename"
# 按名称查找(不区分大小写)
find /path/to/directory -iname "filename"
# 按通配符查找
find /path/to/directory -name "*.txt"按类型查找
bash
#!/bin/bash
# 查找文件
find /path/to/directory -type f
# 查找目录
find /path/to/directory -type d
# 查找符号链接
find /path/to/directory -type l按大小查找
bash
#!/bin/bash
# 查找大于 100M 的文件
find /path/to/directory -size +100M
# 查找小于 10M 的文件
find /path/to/directory -size -10M
# 查找等于 50M 的文件
find /path/to/directory -size 50M按时间查找
bash
#!/bin/bash
# 查找 7 天内修改的文件
find /path/to/directory -mtime -7
# 查找 7 天前修改的文件
find /path/to/directory -mtime +7
# 查找 7 天内访问的文件
find /path/to/directory -atime -7
# 查找 7 天内改变的文件
find /path/to/directory -ctime -7按权限查找
bash
#!/bin/bash
# 查找权限为 755 的文件
find /path/to/directory -perm 755
# 查找权限至少为 755 的文件
find /path/to/directory -perm -755
# 查找权限恰好为 755 的文件
find /path/to/directory -perm /755按所有者查找
bash
#!/bin/bash
# 查找所有者为 user 的文件
find /path/to/directory -user user
# 查找组为 group 的文件
find /path/to/directory -group grouplocate 命令
基本用法
bash
#!/bin/bash
# 查找文件
locate filename更新数据库
bash
#!/bin/bash
# 更新数据库
updatedbgrep 命令
查找文件内容
bash
#!/bin/bash
# 查找文件内容
grep -r "pattern" /path/to/directory
# 查找文件内容(显示文件名)
grep -rl "pattern" /path/to/directory实用示例
示例1:查找大文件
bash
#!/bin/bash
# 查找大于 100M 的文件
find /path/to/directory -size +100M
# 查找最大的 10 个文件
find /path/to/directory -type f -exec ls -lh {} \; | sort -k5 -h | head -10示例2:查找空文件
bash
#!/bin/bash
# 查找空文件
find /path/to/directory -type f -empty
# 查找空目录
find /path/to/directory -type d -empty示例3:查找最近修改的文件
bash
#!/bin/bash
# 查找 7 天内修改的文件
find /path/to/directory -mtime -7
# 查找 24 小时内修改的文件
find /path/to/directory -mtime -1示例4:查找特定权限的文件
bash
#!/bin/bash
# 查找权限为 777 的文件
find /path/to/directory -perm 777
# 查找可执行的文件
find /path/to/directory -perm /111组合查找
组合条件
bash
#!/bin/bash
# 查找名称为 *.txt 且大于 10M 的文件
find /path/to/directory -name "*.txt" -size +10M
# 查找名称为 *.txt 或 *.log 的文件
find /path/to/directory \( -name "*.txt" -o -name "*.log" \)
# 查找名称为 *.txt 且不大于 10M 的文件
find /path/to/directory -name "*.txt" ! -size +10M执行命令
bash
#!/bin/bash
# 查找并删除文件
find /path/to/directory -name "*.tmp" -delete
# 查找并执行命令
find /path/to/directory -name "*.txt" -exec cat {} \;
# 查找并复制文件
find /path/to/directory -name "*.txt" -exec cp {} /backup \;最佳实践
1. 使用 find
bash
# 好的做法
find /path/to/directory -name "*.txt"
# 不好的做法
ls -R /path/to/directory | grep "\.txt$"2. 使用 locate
bash
# 好的做法
locate filename
# 不好的做法
find / -name "filename"3. 使用 grep
bash
# 好的做法
grep -r "pattern" /path/to/directory
# 不好的做法
find /path/to/directory -type f -exec grep "pattern" {} \;总结
文件查找的关键点:
- find 命令:按名称、类型、大小、时间、权限、所有者查找
- locate 命令:快速查找文件
- grep 命令:查找文件内容
- 实用示例:查找大文件、查找空文件、查找最近修改的文件、查找特定权限的文件
- 组合查找:组合条件、执行命令
- 最佳实践:使用
find、使用locate、使用grep
下一节我们将学习文件压缩的使用。