Day 14 08-12 find 查找

1.find 查找概述

为什么要有文件查找,因为很多时候我们可能会忘了某个文件所在的位置,此时就需要通过find来查找。find命令可以根据不同的条件来进行查找文件,例如:文件名称、文件大小、文件修改时间、属主属组、权限、等等方式。同时find命令是Linux下必须掌握的。

find 命令的基本语法如下

命令     路径       选项         表达式                   动作

find   [path...]  [options]    [expression]           [action]

2.find 查找示例

1.find 名称查找

  -name

[root@centos ~]# find ./ -name "*eth0"  -name    按名字查找,分大小写

[root@centos ~]# find ./ -iname "*eth0" -name 按名字查找,不分大小写

2.find 大小查找

  -size

[root@centos ~]# find /etc -size +5M -ls

查找/etc目录下文件大于5M,然后使用-ls 参数以格式显示,这里的-ls 是find自带的

[root@centos ~]# find /etc -size +5M | xargs ls -lh

查找/etc目录下文件大于5M,然后通过管道显示当前文件以人性化-lh详细信息

[root@centos ~]# find /etc -size -1k|xargs ls -lh

查找/etc目录下文件小于1k的,然后通过管道显示当前文件以人性化-lh详细信息

3.find 类型查找

  -type

f 文件

d 目录

l 链接

p 管道文件

s socket文件

c 字符设备

b 块设备

[root@centos ~]# find ./ type f -iname "*-eth0" -ls

查找在当前目录下类型是文件的,并忽略大小写的名称查找为 *-eth0,都以长格式显示

[root@centos ~]# find ./ type d -iname "*-eth0" -ls

查找在当前目录下类型是目录的,并忽略大小写的名称查找为 *-eth0,都以长格式显示

[root@centos ~]# find /bin/ type l -iname "b*" -ls

查找/bin下类型是链接文件的,忽略大小写查找名称为b*的,以长格式显示

[root@centos ~]# find /dev/ -type b -ls

[root@centos ~]# find /dev/ -type c -ls

PS:类型有了,最好还有name 或则 -size

[root@centos ~]# find /etc/ -type f -size +3M -iname "hw*" -ls

查找/etc 下类型为 f 文件的,忽略大小写名称为 "hw*",以长格式显示

4.find时间查找

  -mtime +7

+7 以当前时间为准,查找7天以前的内容(保留了最近7天的数据)

[root@centos ~]# find ./ -type f -mtime +7 -name "file*" -delete

-7 以当前时间为准,查找最近7天的文件,不建议使用(会打印当天的内容)

[root@centos ~]# find ./ -type f -mtime -7 -name "file*"

7 只找第7天的文件 按当前时间算 就只打印第7天的

[root@centos ~]# for i in {01..28};do date -s 201908$i && touch file-$i;done

创建20190801日-0828的文件

[root@centos ~]# find ./ -type f -mtime 7

5.find用户查找

  -user

  -group

  -nouser

  -nogroup

[root@centos ~]# find /home -user oldboy

查找/home下 属主为oldboy 的文件

[root@centos ~]# find /home -group oldboy

查找/home下 属组为oldboy的文件

3.find 动作处理

-delete 只能删除文件,如果要删除目录,需要保证目录为空,否则无法删除

[root@centos ~]# find log/ -type f -name "*.log" -delete

-ok      后面跟自定义shell命令(会提示是否操作)

[root@centos tmp]# find /etc/ -name "ifcfg*" -ok cp -vp {} /tmp \;

-exec    后面跟自定义shell命令 (标准写法 -exec\;)

exec 是将查找到的文件,一个一个的删除

[root@centos tmp]# find /etc/ -name "ifcfg*" -exec cp -vp {} /tmp \;

xargs

xargs 是将文件整体作为一个目标,一次删除

[root@centos tmp]# find /etc/ -name "ifcfg*" | xargs rm -fm

1,我仅记得文件里面的内容,但不记得文件在哪,也不记得文件名是什么,怎么办

[root@centos tmp]# find /etc/ | xargs grep -R "superusers" --color=auto

查找/etc目录下所有文件或目录,将查找到的结果传递给grep命令做筛选 -R 必须要加,递归查找,不加会报错这是目录

4.find 逻辑运算符

  !非,取反

[root@centos ~]# find /home/ ! -user root -ls

查找/home目录下不是 -user root 的文件

-a 与

[root@centos ~]# find /var/ -type f ! -user root ! -a  -name "f*"

-o 或

[root@centos ~]# find /tmp/ ! -user root -o ! -name f

你可能感兴趣的:(Day 14 08-12 find 查找)