一、find查找的语法

二、find查找的分类
find 命令不支持管道技术。
1.按名称查找
[root@10 ~]# find /etc -name "file"
# 用 -iname 表示忽略大小写
[root@10 ~]# find /etc -iname "file"
# 可能不知道名称的全部,不知道的部分用 * 表示
[root@10 ~]# find /etc -name "file-*"
2.按大小查找
[root@10 ~]# find /etc -size +1M
+1M 表示查找大于1M的文件
-1M 表示查找小于1M的文件
1M 表示查找等于1M的文件
3.按类型查找
[root@10 ~]# find /etc -type f
#与之前学习的文件类型一样
f 文件
d 目录
b 块设备文件(磁盘、光盘)
c 字符设备
l 软链接
s socket 进程与进程间的通讯
4.按时间查找
[root@10 ~]# find ./ -iname "file-*" -mtime +7
+7 表示查找7天以前的(不包括当天向前数)
-7 表示查找最近7天的(包括当天)
7 表示查找第7天的(不包括当天,向前数)
常用场景:
查找 /var/log 下以 .log 结尾的文件,并保留最近7天的数据,删除剩余的。
# 通过 +7,把前 7天的列出来,进行删除,留下的就是最近7天的
[root@10 ~]# find /var/log -type f -name "*.log" -mtime +7 -delete
5.按属主和属组查找
#查找属主为oldboy的文件
[root@10 ~]# find /home -user oldboy
#查找属组为root的文件
[root@10 ~]# find /home -group root
-nouser 没有属主
-nogroup 没有属组
三、find动作处理
查找一个文件后,需要对文件进行如何处理(查看、列出、拷贝、删除...),find的默认动作是 -print
-print 打印查找到的内容(默认)
-ls 以长格式的方式打印查找到的内容
-delete 删除查找到的文件(仅能删除空目录)
-ok 后面跟自定义 shell 命令(会提示是否操作)
-exec 后面跟自定义 shell 命令(标准写法 -exec \;)
小结:
我们可以用 -exec 删除、拷贝
#对查找到的内容进行复制,{} 表示存放查找到的内容
[root@10 ~]# find /etc -name "ifcfg*" -exec cp -v {} /tmp \;
#对查找的内容进行删除
[root@10 ~]# find /etc -name "ifcfg*" -exec rm -rf {} \;
拓展:
-exec 因为是一个一个的进行删除,效率低,所以引入了xargs参数,让 find 命令支持管道技术。
[root@10 ~]# find /etc -name "ifcfg*" | xargs rm -rf # 删除效率高
四、特殊情况
当我们不清楚要查找文件名和路径,只记得文件内容是什么,我们可以用 xargs参数,以及grep
[root@10 ~]# find /etc -type f |xargs grep "oldboy" --color=auto #将查找到的结果作为grep的参数
五、find逻辑运算符
-a 与(-and)默认的
-o 或(-or)
! 非(-not)
要点:
当我们用 -o 时,用-ls打印内容,ls会打印离他最近的,有时候就需要用到 \ ( )\ 来变成一个整体。
\ 转义字符,去掉符号的特殊含义,回归普通字符
grep "1$" 1.txt 表示匹配以1结尾的行
grep "1\$" 1.txt 表示匹配含有1$的行, \ 让特殊符号 $ 回归原始意义
例如
[root@10 ~]# mkdir /root/dir1
[root@10 ~]# touch /root/dir1/file{1..10}
# ls 只会打印显示 file9 的长格式
[root@10 ~]# find /root/dir1 -name "file5" -o -name "file9" -ls
# ls 会打印 file5 和 file9 的长格式
[root@10 ~]# find /root/dir1 \( -name "file5" -o -name "file9" \) -ls
网友评论