Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

Linux常用查找命令 #116

Open Qingquan-Li opened 5 years ago

Qingquan-Li commented 5 years ago

Linux常用查找命令

一、locate

locate 命令其实是 find -name 的另一种写法,但是要比后者快得多,原因在于它不搜索具体目录,而是搜索一个本地文件数据库(目录为 /var/lib/locatedb ),这个数据库中含有本地所有文件信息。 Linux 系统自动创建这个数据库,并且每天自动更新一次,所以使用 locate 命令查不到最新变动过的文件。为了避免这种情况,可以在使用 locate 命令之前,先使用 updatedb 命令,手动更新数据库。

实例:

$ sudo updatedb        # 手动更新数据库
$ sudo locate test.git # 搜索test.git文件所在的目录
$ locate /etc/sh       # 搜索etc目录下所有以sh开头的文件。
$ locate -i /data/a    # 搜索/data目录下,所有以a开头的文件,并且忽略大小写


二、whereis

whereis 命令只能用于程序名的搜索,而且只搜索二进制文件(参数为 -b )、 man 说明文件(参数为 -m )和源代码文件(参数为 -s )。如果省略参数,则返回所有信息。

实例:

$ whereis pip
pip: /usr/local/bin/pip3.5 /usr/local/bin/pip


三、which

which 命令用于搜索某个系统命令的位置,并且返回第一个搜索结果。也就是说,使用 which 命令,就可以看到某个系统命令是否存在,以及执行的到底是哪一个位置的命令。

实例:

$ which python3
/usr/bin/python3


四、find

使用 find 命令文件非常方便。但是 find 在寻找数据时相当耗硬盘,简直执行简单的查找时可以使用 locate

$ sudo find <path> <expression> <cmd>

find命令常用选项及实例

  1. -name 按文件名查找文件

    $ sudo find / -name test.git # 在系统根目录下查找名字为test.git的文件
    $ find . -name "*.py"   # 在当前目录中查找扩展名为“py”的文件
  2. -perm 按文件权限来查找文件

    $ find . -perm 755 # 在当前目录下查找文件权限位为755的文件,即文件属主可以读、写、执行,其他用 
    户可以读、执行的文件
  3. -user 按文件属主来查找文件

    $ find ~ -user qcloud-git # 在$HOME目录中查找文件属主为qcloud-git的文件
  4. -group 按文件所属的组来查找文件

    $ find ~ -group qcloud-git # 在$HOME目录下查找属于qcloud-git用户组的文件
  5. -mtime -n +n 按文件的更改时间来查找文件, -n 表示文件更改时间距现在 n 天以内, +n 表示文件更改时间距现在 n 天以前

    $ find . -mtime -3 # 在当前目录下查找更改时间在3日以内的文件
    $ find . -mtime +7 # 在当前目录下查找更改时间在7日以前的文件
  6. -nouser 查找没有属主的文件,即该文件的属主在 /etc/passwd 中不存在

    $ find /home -nouser # 在/home目录下没有属主的文件
  7. -nogroup 查找没有所属组的文件,即该文件所属的组在 /etc/groups 中不存在

    $ find /data/repositories/test.git –nogroup # 在/data/repositories/test.git目录下没有属组的文件
  8. -type 查找某一类型的文件: b 块设备文件、 d 目录、 c 字符设备文件、 p 管道文件、 l 符号链接件、 f 普通文件

    $ find /data/repositories/test.git -type d    # 在/data/repositories/test.git目录下查找所有的目录
    $ find /data/repositories/test.git ! -type d  # 在/data/repositories/test.git目录下查找除目录以外的所有类型的文件
    $ find /data/repositories/test.git -type l    # 在/data/repositories/test.py目录下查找所有的符号链接文件
  9. -size n[c] 查找文件长度为 n 块的文件,带有 c 时表示文件长度以字节计算

    $ find /home/qcloud-git -size +1024000c # 在/home/qcloud-git目录下查找文件长度大于1M字节的文 
    件
    $ find /home/qcloud-git -size +10       # 在当前目录下查找长度超过10块的文件(一块等于512字节)


五、grep

$ grep [选项] pattern [文件名]

选项:

pattern 为所要匹配的字符串,符号含义如下

实例:

$ ls -l | grep '^a' # 通过管道过滤ls -l输出的内容,只显示以a开头的行。
$ grep 'def' w*     # 显示以w开头的文件中包含test的行。