卡饭网 > linux > 正文

Linux find命令10种使用方法技巧分享

来源:本站整理 作者:梦在深巷 时间:2013-04-27 03:10:28

find命令的工作方式是沿着文件层次结构向下遍历,匹配符合条件的文件,并执行相应的操作。

1、根据文件名或正则表达式匹配搜索

选项-name的参数指定了文件名所必须匹配的字符串,我们可以将通配符作为参数使用,“*.txt”匹配所有以.txt结尾的文件名。

复制代码

代码如下:

[root@localhost test]# touch {data,log,file,File,LOG}_{1,2,3,4,5,6}_{.txt,.pdf,.log,.conf}
[root@localhost test]# find . -name "*.txt" –print

如果想匹配多个条件中的一个,可以使用-o参数。

复制代码

代码如下:

[root@localhost test]# find . /( -name "*.txt" -o -name "*.log" /)

选项-iname忽略字母大小写
选项-path的参数可以使用通配符来匹配文件路径或文件。

2、否定参数

find 用 “!”来否定参数,匹配所有不以.txt结尾的文件名。

复制代码

代码如下:

[root@localhost test]# find . ! -name "*.txt" –print

3、基于目录深度的搜索

find命令在使用时会遍历所有的子目录,我们可以采用-maxdepth和-mindepth来限制find命令遍历的深度。
-maxdepth: 指定最大深度;
-mindepth:指定最小深度。

复制代码

代码如下:

[root@localhost ~]# find . -maxdepth 1 -type f

列出当前目录的所有普通文件,这两个命令要紧跟在目标路径之后。

4、根据文件类型搜索

复制代码

代码如下:

find . –type d –print

文件类型 类型参数
普通文件 f
符号文件 l
目录 d
字符设备 c
块设备 b
套接字 s
fifo p

5、根据文件时间进行搜索

Linux文件系统中每一个文件都有三种时间戳
访问时间(-atime):用户最近一次访问文件的时间;
修改时间(-mtime):文件内容最后一次被修改的时间。
变化时间(-ctime):文件元数据(metadata,例如权限或所有权)最后一次改变的时间。
-atime,-mtime,-ctime作为时间参数,单位是天,可以使用+表示大于,-表示小于。

复制代码

代码如下:

[root@localhost ~]# find . -type f -atime 7
#打印出正好在7天前被访问过的文件
[root@localhost ~]# find . -type f -mtime +7
#打印修改时间大于7天的文件
[root@localhost ~]# find . -type f -ctime -7
#打印出修改时间小于7天的文件

类似的参数还有,-amin(访问时间),-mmin(修改时间),-cmin(变化时间),以分钟为单位。
find另一个漂亮的特性是-newer参数,我们可以指定一个用于比较时间戳的参数文件,然后找出比参数文件更新的所有文件。
find . –type f –newer file.txt
p 在当前目录找出比file.txt修改时间更长的所有文件。
6、基于文件大小的搜索
搜索可以使用的单位
b——块(512字节); c——字节; w——字(2字节);
k——千字节 ; M——兆字节; G——吉字节。

复制代码

代码如下:

[root@localhost tmp]# find . -type f -size 2k
#等于2k的文件
[root@localhost tmp]# find . -type f -size +2k
#大于2k的文件
[root@localhost tmp]# find . -type f -size -2k
#小于2k的文件

7、删除匹配的文件

-delete可以用来删除find查找到的匹配文件。

复制代码

代码如下:

[root@localhost tmp]# find . -type f -name ".sWp" –delete
#删除当前目录下所有的.swp文件

8、基于文件权限和所有权的匹配

复制代码

代码如下:

[root@localhost tmp]# find . -type f -perm 644
#查找当前目录权限为644的文件
[root@localhost tmp]# find . -type f -user reed
#查找当前目录文件所有者为reed的文件

9、结合find 执行命令或动作

find命令可以借助选项-exec与其他命令进行结合。

复制代码

代码如下:

[root@localhost tmp]# find . -type f -user reed -exec chown cathy {} /;
#将当前目录文件拥有者为reed的文件改为cathy

{ }是一个特殊的字符串,对于每一个匹配的文件,{ }会被替换成相应的文件名。

复制代码

代码如下:

[root@localhost test]# find . -type f -mtime +10 -name "*.log" -exec cp {} /data/bk_log /;
#将当前目录大于10天的log文件复制到/data/bk_log目录
[root@localhost test]# find /tmp/test/ -type f -name "*.txt" -exec printf "Text file: %s/n" {} /;
Text file: /tmp/test/File_6_.txt
Text file: /tmp/test/file_4_.txt
Text file: /tmp/test/data_3_.txt
Text file: /tmp/test/data_1_.txt
#列出目录的所有txt文件

10、跳过指定的目录

有时间我们查找时需要跳过一些子目录

复制代码

代码如下:

[root@localhost test]# find . /( -name "jump_dir" -prune /) -o /( -type f -print /)
# /( -name "jump_dir" -prune /) 指定要跳过的子目录的名字

相关推荐