find
文件与目录
用法
find [path] -name '[pattern]' -type f遍历目录树逐个匹配条件;把模式写成 -name '*.log' 加引号,否则 shell 会先把它展开。
常用选项
| 选项 | 含义 |
|---|---|
| -name | Match the file name, case sensitive; -iname ignores case |
| -type | Restrict to f (file), d (directory) or l (symlink) |
| -size | Filter by size, as in -size +100M |
| -mtime | Filter by age in days, as in -mtime +7 |
| -maxdepth | Limit how deep to walk; GNU wants it before the tests |
| -delete | Delete every match, no confirmation |
| -exec | Run a command on each hit, ending with \; or + |
| -print0 | Separate results with NUL, to pair with xargs -0 |
示例
find . -name '*.log' -mtime +7 -deleteDeletes log files older than a week.
find / -type f -size +1G 2>/dev/nullFinds files over a gigabyte, hiding permission errors.
find . -name '*.jpg' -exec mv {} photos/ +Moves every JPEG it finds.
移动、删除和查找。有些命令不会再问一遍,所以顺手加 -i 是在救自己。
怎么看
- 方括号 [ ] 表示这部分可以不写。
- 省略号 … 表示可以写多个。
- 选项区分大小写——有些命令里 -r 和 -R 不是一回事。
常见问题
Q. find 是做什么的?
遍历目录树逐个匹配条件;把模式写成 -name '*.log' 加引号,否则 shell 会先把它展开。
Q. 怎么写?
find [path] -name '[pattern]' -type f —— 方括号表示可以省略的部分。
Q. 值得记的选项有几个?
这里列了 8 个,完整列表在 man find。这条命令属于文件与目录。
相关命令
man 手册: man find