天天看点

文件的搜索一、 locate二、 find

文件的搜索一、 locate二、 find
在使用Linux系统时,有时会因为文件创建时间很久,而记不得全全名,只能记得模糊的几个关键字时,就可以使用文件查找命令来进行快速搜索。Linux提供最常用的搜索方有两个工具locate与find。不过在日常中还是使用find比较多,因为他具有时效性。

一、 locate

locate的搜索是基于数据库的,数据库会在系统空闲时每天更新一次。locate是非时效性的(新文件没有加入数据库导致不能被查找到)。

1. 特点

可以模糊查找、查找速度快、搜索匹配的是文件的全路径,不只是文件名

2. 手动更新数据库

手动更新会占用系统资源,所以要在系统空闲时进行更新

[root@centos7 app]# updatedb           

4. 搜索

[root@centos7 app]# locate -i aubin                             # -i不区分大小写
[root@centos7 app]# locate -i aubin -n 10                       # -n 只显示前几个
[root@centos7 app]# locate -r '\.conf$'                         # -r 支持正则表达式           

二、 find

查找速度慢、精确查找、具有时效性

2. 命令格式

find <路径> <选项> <动作>

3. 命令选项

  • 查找深度,搜索的目录层级
    [root@centos7 app]# find -maxdepth
    [root@centos7 app]# find -mindepth
    [root@centos7 app]# find / -name aubin           
  • 指定目录/文件名

    支持使用glob

    *, ?, [], [^]

    ( [ ]为匹配单个字符的范围)
    [root@centos7 app]# find / -name aubin
    [root@centos7 app]# find / -name a?c
    /sys/fs/selinux/avc
    [root@centos7 app]# find / -name [etc]
    /var/lib/yum/yumdb/t
    /var/lib/yum/yumdb/e
    /var/lib/yum/yumdb/c
    #
    -inum n 按inode号查找
    -samefile filename 与filename文件相同inode号的文件
    -links n 链接数为n的文件
    -regex "PATTERN":以PATTERN匹配整个文件路径字           
  • 查找条件
    -user USERNAME                  #查找属主为指定用户(UID)的文件
    -group GRPNAME                  #查找属组为指定组(GID)的文件
    -uid UserID                     #查找属主为指定的UID号的文件
    -gid GroupID                    #查找属组为指定的GID号的文件
    -nouser                         #查找没有属主的文件
    -nogroup                        #查找没有属组的文件           
    -type
    f: 普通文件 
    d: 目录文件 
    l: 符号链接文件 
    s:套接字文件 
    b: 块设备文件 
    c: 字符设备文件 
    p: 管道文件           
  • 或与非
    与:-a
    或:-o
    非:-not, !           
  • 或的实际应用

    在使用-o 时如果后面要跟动作,要加括号,如下面例子,否则的话只会输出靠近ls的搜索结果

[root@centos7 app]# find /  -user li -o -user aubin -exec ls -al {} \; 
[root@centos7 app]#  find /  \( -user li -o -user aubin \) -exec ls -al {} \;           
  • 按大小查找
    -size  nk                    #(n-1k,nk]
    -size  10k                   #(9k,10k]
    -size -10k                   #[0k,10k]
    -size +10k                   #(10k,无穷)
    #
    -size 1024k                  #(1023k,1024k]
    -size 1M                     #(0M,1M]           
  • 按时间戳排序
    #以天为单位
    -atime
    -mtime
    -ctime
    [root@centos7 app]# find /app/ -atime 1
    [root@centos7 app]# find /app/ -atime +1
    [root@centos7 app]# find /app/ -atime -1
    #
    #以分钟为单位
    -amin -mmin -cmin