实例讲解linux强大的find命令

《实例讲解linux强大的find命令》 find命令思维导图

Find命令是linux中最常用且重要的命令之一,用于检索文件所在的位置,可以根据多种参数组合进行检索:文件名称,文件权限,文件属组,文件类型,文件大小等。

虽然man find手册有关于find的详细说明,可缺乏实例的说明文档显得干巴巴,对初学者很不友好。导致初学者对于find产生这样的印象:“我知道find很强大,但不知道用在什么场景,该怎么用”。

再强大的工具,只有会用,用得好,才能体现出其价值。

基于此,本文将用实例讲解find命令常用场景:

基本使用

-name 指定文件名

$ find /etc -name passwd
/etc/cron.daily/passwd
/etc/pam.d/passwd
/etc/passwd

find会对指定路径进行递归查找

-iname 忽略大小写

$ find . -iname test.txt
./TesT.txt
./Test.txt
./test.txt

-type d 查找目录

$ find . -type d -name dir1
./dir1

-type f 查找文件

$ find . -type f -name test.php
./test.php

查找某一类文件

$ find . -type f -name "*.php"
./test.php
./test1.php
./test2.php

* 表示通配符

根据权限查找

查找权限为777的文件

$ find . -type f -perm 777 -print

-print 将结果打印

查找权限不为777的文件

$ find . -type f ! -perm 777

! 反选

查找可执行文件

即查找所有用户都拥有x权限的文件

$ find . -type f -perm /a=x

找到777权限的文件并将其改为644

$ ll
-rwxrwxrwx 1 root root 0 9月  17 22:01 test

$ find -type f -perm 777 -print -exec chmod 644 {} \;
./test

$ ll                                                 
-rw-r--r-- 1 root root 0 9月  17 22:01 test

查找并删除单一文件

$ find . -type f -name "test" -exec rm -f {} \;

查找并删除多个文件

$ find . -type f -name "*.txt" -exec rm -f {} \;

查找所有空文件

$ find /tmp -type f -empty

查找所有空目录

$ find /tmp -type d -empty

查找所有隐藏文件

$ find . -type f -name ".*"

根据属主/属组查找文件

$ find /etc -user senlong -name passwd

$ find /etc -user root -name passwd   
/etc/cron.daily/passwd
/etc/pam.d/passwd
/etc/passwd

$ find /etc -group root -name passwd
/etc/cron.daily/passwd
/etc/pam.d/passwd
/etc/passwd

根据文件时间查找

50天前修改过的文件

$ find . -mtime 50

大于50天小于100天前修改过的文件

$ find . -mtime +50 -mtime -100

根据文件大小查找

查找大小为50M的文件

$ find / -size 50M

查看大小为50M至100M的文件

$ find / -size +50M -size -100M

查找大于100M的log文件并删除

$ find / -type f -name "*.log" -size +100M -exec rm {} \;

思维导图源文件下载

参考链接

    原文作者:塞亚猫
    原文地址: https://www.jianshu.com/p/d586278e280b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞