首页·终端命令

find

文件与目录

用法

find [path] -name '[pattern]' -type f

遍历目录树逐个匹配条件;把模式写成 -name '*.log' 加引号,否则 shell 会先把它展开。

常用选项

选项含义
-nameMatch the file name, case sensitive; -iname ignores case
-typeRestrict to f (file), d (directory) or l (symlink)
-sizeFilter by size, as in -size +100M
-mtimeFilter by age in days, as in -mtime +7
-maxdepthLimit how deep to walk; GNU wants it before the tests
-deleteDelete every match, no confirmation
-execRun a command on each hit, ending with \; or +
-print0Separate results with NUL, to pair with xargs -0

示例

find . -name '*.log' -mtime +7 -delete

Deletes log files older than a week.

find / -type f -size +1G 2>/dev/null

Finds 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