find 按条件查找文件
根据预设的条件递归查找对应的文件
find [目录] [条件1] [-a|-o] [条件2]
//【and:同时满足两个条件、or:满足两个条件之一】
作用: find 指定查找的目录 指定条件(文件的特征) 指定动作(对结果怎样处理)
常用条件表示:
-type 类型(f、d、b(快设备文件)、c(字符设备文件))
类型:f:文件 d:目录 l:快捷方式
[root@server0 ~]# find /boot/ -type l #查找是快捷方式的文件,可通过ll查询链接情况
[root@server0 ~]# find /boot/ -type f #查找是文件
[root@server0 ~]# find /boot/ -type d #查找是目录
-name 文档名称
在指定的目录查找指定名称的文件
[root@server0 ~]# find /boot -name vmlinuz*
[root@server0 ~]# find /etc -name passwd
[root@server0 ~]# find /etc -name *.conf
查找/root/目录下,以nsd开头的,并且是文件
[root@server0 ~]# find /root -name "nsd*" -a -type f
查找/root/目录下,以nsd开头的,并且是目录
[root@server0 ~]# find /root -name "nsd*" -a -type d
查找系统中,所有者是student用户,并且是文件的
[root@server0 ~]# find / -user student -type f
-size +|- 文件大小(k、M、G)
[root@server0 ~]# find /boot/ -size +10M
//一般用+比较多,很少用小于(太多了)
//当-1k、-1M、-1G时,系统无法识别,无法使用
-mtime +|- 文件内容修改天数
n n为数字,意义在n天之前的“一天之内”被更改过的文件
+n 列出在n天之前(不含n天本身)被更改过的文件名
-n 列出在n天之内(含n天本身)被更改过的文件名
[root@server0 ~]# find /root/ -mtime -10
//查找最近10天之内修改过的文档
[root@server0 ~]# find /root/ -mtime +1000
//查找1000天之前修改过的文档
-user 用户名
查找所有者是哪个用户的文档
[root@server0 ~]# useradd dc
[root@server0 ~]# find /home/ -user dc
-group 组名 与-user选项类似
find结果处理
find ...-exec处理命令{} \; 将查找到的结果交给处理命令进行处理(find独有的选项)
优势:以{}代替每一个结果,逐个处理,遇\;结束
[root@server0 ~]# find /boot/ -name "vm*" -exec cp -r {} /root/findfiles/ \;
[root@server0 ~]# ls /root/findfiles
[root@server0 ~]# find / -user student -type f -exec cp -r {} /root/findfiles/ \;
[root@server0 ~]# ls -A /root/findfiles
[root@server0 ~]# find /boot -size +10M -exec cp -r {} /root/findfiles/ \;
[root@server0 ~]# ls /root/findfiles
###############################################################################
Locate 文件名
作用:locate 查找一个文件所在位置,查找速度快,需要通过updatedb生成数据库
which 专门用于查找外部命令,程序文件所在位置
格式:which 命令名称
[root@server0 ~]# which echo
[root@server0 ~]# which ls
###############################################################################
案例:查找并处理文件
采用不少于两种方法完成以下任务:
找出所有用户 student 拥有的文件
把它们拷贝到 /root/findfiles/ 文件夹中
步骤一:确认能找到指定的文件
[root@server0 ~]# find / -user student -type f
对于上述操作中出现的/proc信息忽略即可。
步骤二:处理找到的文件
1)创建目标文件夹 # mkdir /root/findfiles
2)拷贝找到的文件到目标文件夹
以下两种方法任选一种:
# find / -user student -type f -exec cp -p {} /root/findfiles/ \;
或者
# \cp -p $(find / -user student -type f) /root/findfiles/
3)确认拷贝结果
[root@server0 ~]# ls -lhA /root/findfiles/