【Linux系列教程】查找的使用

使用方法

# find 目录名称  查找条件 [-exec 命令 \;]

一、查找条件

1.按照文件名查找

  • -name
  • -iname 忽略大小写
[root@localhost ~]# find /opt/test/ -name "*.txt"
[root@localhost ~]# find /opt/test/ -name "*.txt" | wc -l

[root@localhost ~]# find /opt/test/ -iname "*.txt"	#忽略大小写

2.按照文件大小查找

  • -size
[root@localhost ~]# find /etc/ -size +2M	#查找大于2M

[root@localhost ~]# find /etc/ -size -2M	#查找小于2M

3.按照文件类型查找

  • -type
    • f 普通文件
    • d 目录
    • l 链接文件
[root@localhost ~]# find /etc/ -type f

4.按照文件创建时间查找

  • -ctime
[root@localhost ~]# find /etc/ -ctime +3	#3天之前

[root@localhost ~]# find /etc/ -ctime -3	#3天之内

5.按照文件最后一次修改时间查找

  • -mtime
[root@localhost ~]# find /etc/ -mtime -2	#2天之内

[root@localhost ~]# find /etc/ -mtime +2	#2天之前 

6.多条件查找(重要)

  • -a 并且
  • -o 或者
[root@localhost ~]# find /etc/ -name "*.conf" -a -size +20k	#查找/etc下的名字包含“.conf”并且文件大于20K的文件

[root@localhost ~]# find /etc/ -mtime -3 -a -size +10k -a -name "*.conf" 	#查找/etc下最近修改时间小于3天,并且文件大于10k,并且文件名包含“.conf”的文件
[root@localhost ~]# find /etc/ -name "*.conf" -o -size +1M	#查找/etc下名字包含“.conf”的文件或者大于1M的文件

7. -maxdepth 指定查找目录层级

查找/etc目录, 及它下面的2层目录中软链接文件
[root@localhost ~]# find /etc/ -type l -maxdepth 2

二、exec 添加命令操作

  • -exec 命令 \;
    • 对查找结果进行某某操作
[root@localhost ~]# find /opt/test/ -name "*.mp3" -exec rm -rf {} \;	#查找/opt/test下名字包含“.mp3”的文件,执行删除所有文件

[root@localhost ~]# find /opt/test/ -name "*.jpg" -exec cp {} /tmp \;	#查找/opt/test下名字包含“,jpg”的文件,执行复制到/tmp下

[root@localhost ~]# find /etc/ -name "*.conf" -a -size +30k -exec ls -lh {} \;	#查找/etc下名字包含“。conf”的文件并且文件大于30k,执行查看详细信息