文件查找之find命令
命令:find
参数类型:
文件类型 -type
文件名称 -name
文件大小 -size
文件修改时间 -mtime
文件属主和属组 -user -group
按文件名查找
-name
//1.查找包含ifcon-eth1名称的文件
[root@study ~]# find /etc -name "ifcfg-eth1"
//2.查找包含txt的文件
[root@study ~]# find /etc -name "*ifcfg-eth1*" // **表示只要包含ifcfg-eth1的名称都符合要求
//3.-i 忽略大小写
[root@study ~]# find /etc -iname "ifcfg-eth1"
//4.查找以.log结尾的文件
[root@study ~]# find /etc -iname "*.log" //*表示.log前可以是任意字符
按文件类型查找
-type d
//文件类型:
//f :文件
[root@study ~]# find /dev -type f
//d:目录
[root@study ~]# find /dev -type d
//l:链接
[root@study ~]# find /dev -type l
//b:块设备
[root@study ~]# find /dev -type b
//c:字符设备
[root@study ~]# find /dev -type c
//s:套接字
[root@study ~]# find /dev -type s
按文件大小查找
-size
//1.查找大于5M的文件()
[root@study ~]# find /etc -size +5M
2.查找等于5M的文件
[root@study ~]# find /etc -size 5M
3.查找小于5M的文件
[root@study ~]# find /etc -size -5M
按文件时间查找
-mtime
示例:
1.查找7天以前的文件(不会打印当天的文件)=====( 保留了最近7天的数据)
[root@study ~]# find ./ -iname "file-*" -mtime +7
2.查找最近7天的文件,不建议使用(会打印当天的文件)
[root@study ~]# find ./ -iname "file-*" -mtime -7
3.查找第7天文件(不会打印当天的文件)
[root@study ~]# find ./ -iname "file-*" -mtime 7
实际案例:本地文件保留最近7天的备份文件, 备份服务器保留3个月的备份文件
find /backup/ -iname "*.bak" -mtime +7 -delete
find /backup/ -iname "*.bak" -mtime +90 -delete
按照属主和属组查找
-user
-group
1.查找属主是jack
[root@study ~]# find /home -user jack
2.查找属组是admin
[root@study ~]# find /home -group admin
3.查找属主是jack, 属组是admin
[root@study ~]# find /home -user jack -group admin
4.查找属主是jack, 并且属组是admin
[root@study ~]# find /home -user jack -a -group admin
5.查找属主是jack, 或者属组是admin
[root@study ~]# find /home -user jack -o -group admin
6.查找没有属主
[root@study ~]# find /home -nouser
7.查找没有属组
[root@study ~]# find /home -nogroup
8.查找没有属主或属组
[root@study ~]# find /home -nouser -o -nogroup
动作处理
默认动作(-print)打印到文件
-ls 使用长格式打印文件
[root@study ~]# find /etc -name "ifcfg*" -print
-delete 删除文件,不能删除目录
[root@study ~]#find /etc -name "ifcfg*" -delete
-ok 后面可以跟上自定义的shell命令,并且需要一个一个确认
[root@study ~]#find /etc -name "ifcfg*" -ok cp -v {} /tmp \;
-exec 后面跟自定义命令 (-exec 命令内容 /;)固定格式。有时候要根据命令添加 "\(\)"进行界定
[root@study ~]# find /etc -name "ifcfg*" -exec rm -f {} \;
[root@study ~]# find /etc -name "ifcfg*" -exec cp -v {} /tmp \;
find逻辑运算符
符号 | 作用 | 等价 |
---|---|---|
-a | 与 | and |
-o | 或 | or |
! | 非 | -not |
示例:
//1.查找当前目录下,属主不是root的所有文件
[root@study ~]# find . -not -user root
[root@study ~]# find . ! -user root
//2.查找当前目录下,属主属于oldxu,并且大小大于1k的文件
[root@study ~]# find /etc -type f -user oldxu -size +1k
[root@study ~]# find /etc -type f -user oldxu -a -size +1k
[root@study ~]# find /etc -type f -user oldxu -and -size +1k
//3.查找当前目录下的属主为root或者以xml结尾的普通文件
[root@study ~]# find . -type f \( -user root -o -name "*.xml" \) -ls