四剑客之四find

find,查找,在指定目录中查找文件
用法:
find 目录 指定类型 指定名字
-type:什么类型的文件,f表示文件,d表示目录
-name:文件名
-size:根据文件大小查找,+表示大于,-表示小于,+10k(小写k) +10M(大写M)G
-mtime:根据修改时间找文件;+7(表示7天之前),-7(7天之内)

-perm /+x:众多权限中,有执行权限的;


基础案例:find命令默认做的是精确查找。
[root@web01 ~]# find /etc/ -type f -name 'hostname'
[root@web01 ~]# find / -type f -name 'ls'

也可以作模糊查找
在/etc/查找以.conf结尾的文件;
[root@web01 ~]# find /etc/ -type f -name '*.conf'
注:*,代表任意符号或所有

根据大小查找文件
[root@web01 ~]# find /etc/ -type f -size +10k

根据时间查找
一般时根据文件的修改时间进行查找,工作中主要用于查找系统日志文件,旧的日志文件,比如7天之前的文件;
[root@web01 ~]# find /etc/ -type f -mtime -7 //最近7天
[root@web01 ~]# find /etc/ -type f -mtime +7 //7天之前的文件


综合案例:
找出/etc/下以.conf结尾大于10kb修改时间在7天之前的文件
[root@web01 ~]# find /etc/ -type f -name '*.conf' -size +10k -mtime +7

进阶案例:
查找文件的时候指定最多找多少层目录
[root@web01 ~]# find / -maxdepth 2 -type f -name '*.conf'
-maxdepth:指定层数
查找的时候不区分大小写
[root@web01 ~]# find /etc/ -type f -iname '*.conf'
find还可以根据权限查找;
find还可以根据用户名查找;查找属于某个用户的文件;

find 命令与其他命令配合
find找出想要的文件删除,看详细信息,显示文件内容,过滤
find找出文件进行打包压缩
find找出文件后复制或移动

案例:
find找出想要的文件删除,看详细信息,显示文件内容,过滤
先准备环境
[root@web01 find]# touch test{1..10}.txt
find找出/find/中以.txt结尾的文件并显示详细信息
方法1:find + ls/ find + rm /find + cat/head/ find + grep
find不要与交互命令配合使用;
[root@web01 ~]# ls -lh `find /mclind/find/ -type f -name '*.txt'`
方法2:find | xargs
[root@web01 ~]# find /mclind/find/ -type f -name '*.txt' | xargs ls -l
find /mclind/find/ -type f -name '*.txt' | ls -l //这种方法失败了,为什么?
前面的命令通过管道传递给后面的命令,传递的是字符串;
这个命令ls中传递文字符号就不行,传递参数;
所以上面的命令相当于find白白浪费了,仅仅执行了下ls -lh而已
如何解决:加上xargs上就可以了。

注:如果用cp,需要注意写法,因为传递的参数是放在的最后,cp的参数-t,是将目标文件夹放在了前面,解决了这个问题;mv也有这个-t选项;

[root@web01 ~]# find /mclind/find/ -type f -name '*.txt' | xargs cp -a -t /mclind/findCp/

方法3:find + -exec方法
[root@web01 ~]# find /mclind/find/ -type f -name '*.txt' -exec ls -lh {} \;

[root@web01 ~]# find /mclind/find/ -type f -name '*.txt' -exec tar zcf /tmp/find.tar.gz {} + //用tar命令的时候,最后用+,因为这个的话,是等find命令执行完,结果都放{}里才执行tar,否则,就是find出一条结果,tar一个文件,且文件名都一样,最后就是最后一个结果覆盖了之前的结果;

posted @ 2022-12-17 16:18  mclind  阅读(20)  评论(0编辑  收藏  举报