Linux find命令是命令行上非常有用和方便的搜索文件的命令。它可用于根据各种搜索标准查找文件,如权限,用户所有权,修改时间/日期,大小等。在这篇文章中,我们将学习使用find命令以及它支持的各种选项。
大多数Linux发行版find命令默认是可用的,因此你不必安装任何软件包。在Linux上,如果你想高效的使用Linux命令行,find命令是必须学习的。
find location comparison-criteria search-term
配置项
-name 按照文件名查找文件,不忽略大小写
-iname 按照文件名查找文件,忽略大小写
-type 按照文件类型查找文件 d文件夹/f普通文件/l链接文件
-size 按照文件大小查找 c/k/M/G
-perm 按照权限查找
-user 按照用户名查找
常用动作
-exec 命令体 {} ; 对符合条件的文件执行所给的Linux 命令,而不询问用户是否需要执行该命令,命令的末尾必须以\;结束
-ls 详细列出所找到的所有文件
-print 在标准输出设备上显示查找出的文件名
xrag
列出当前目录及子目录下的所有文件
root@service-org:~/config# find
.
./ding.php
./horizon.php
./database.php
./session.php
搜索指定目录或路径
root@service-org:~# find config
config
config/ding.php
config/horizon.php
config/database.php
./session.php
通过文件名搜索文件
root@service-org:~# find config -name "ding.php"
config/ding.php
忽略大小写
find config -iname "ding.php"
模糊
find config -iname "*.php"
find config -iname "?ing.php"
限制目录遍历的深度
默认情况下,find命令递归的遍历整个目录树。非常消耗时间和资源。然而,可以指定目录遍历的深度。
find ./test -maxdepth 2 -name '*.php'
反转匹配
也可以搜索与指定名称或模式不匹配的文件,当我们知道要从搜索中排除哪些文件时,这很有用。
find ./test -not -name '*.php'
./test
./test/abc.txt
./test/subdir
find ./test ! -name '*.php'
组合多个搜索条件
find ./test -name 'abc*' ! -name '*.php'
find ./test -name '*.php' -o -name '*.txt'
仅搜索文件或目录
# find ./test -name 'abc*'
./test/abc.txt
./test/abc
Only files
# find ./test -type f -name 'abc*'
./test/abc.txt
Only directories
# find ./test -type d -name 'abc*'
./test/abc
一起搜索多个目录
# find ./test ./dir2 -type f -name 'abc*'
./test/abc.txt
./dir2/abcdefg.txt
查找特定权限的文件
# find . -type f -perm 0644
./abc.txt
./cool.php
./subdir/how.php
./abc.php
查找特殊用户拥有的文件
find . -user root
搜索属于组的文件
find . -group hjm
根据时间搜索文件
查找访问时间距当前日期N天的文件
# find / -atime 50
查找修改时间在50以前,100天以内的所有文件
# find / -mtime +50 -mtime -100
查找最近N分钟内属性更改的文件
# find . -cmin -60
查找最近1小时内内容更改的文件
# find / -mmin -60
根据文件大小搜索
查找指定大小的文件
# find / -size 50M
查找文件大小在指定范围内的文件
# find / -size +50M -size -100M
查找空文件和目录
# find /etc -type f -empty