Unix 下的查找文件的工具 find

- 在某个目录下所有子目录中搜索某个名字文件

find /some/dir -iname "*.txt"
find /some/dir -name "*.txt"
find /some/dir -iregex "*.txt"
find /some/dir -regex "*.txt"

iname 表示不区分大小写, name 表示区分大小写。 他们都是按照 shell 的文件名称扩展方式扩展 *? 的。 如果使用 regexp 那么表示用正则表达式来 匹配文件名称。 iregexp 表示不区分大小写的正则表 达式。

- 在某个目录下所有子目录中搜索某个名字,某种类型的文件

find /some/dir -iname "*.txt" -type d
find /some/dir -name "*.txt" -type f

type 后面的字母表示文件类型。

b block (buffered) special
c character (unbuffered) special
d directory
p named pipe (FIFO)
f regular file
l symbolic link
s socket
D door (Solaris)

find 命令和 bash 结合可以 有很多用处

例如,把所有以 txt 文件结尾的文件,改名成为以doc 结尾的文件,包括所有子目录。

for i in $(find -iname "*.txt"); do
   mv "$i" "${i%%.txt}.doc" ;
done

例如,删除所有以 bak 为扩展名称的文件。

find . -iname "*.bak" | xargs rm