find 搜索命令

2016-05-29

find 搜索命令

which 查找可执行文件的绝对路径

which 只能用来查找 PATH 环境变量中出现的路径下的可执行文件。

[root@localhost ~]# which vi
/bin/vi
[root@localhost ~]# which cat
/bin/cat

whereis 查找文件

它是通过预先生成的一个文件列表库去查找跟给出的文件名相关的文件。

语法 whereis [-bmsu][文件名称]

-b:只找 binary 文件

-m:只找在说明文件 manual 路径下的文件

-s:只找 source 来源文件

-u:没有说明档的文件

[root@localhost ~]# whereis ls
ls: /bin/ls /usr/share/man/man1/ls.1.gz

这个命令类似于模糊查找,只要文件名包含这个”ls“字符就会列出来。

locate 查找文件

类似于 whereis,也是通过查找预先生成的文件列表库来告诉用户要查找的文件在哪里。若没有这个命令,安装软件包 mlocate。

[root@localhost ~]# yum install -y mlocate
[root@localhost ~]# locate passwd
locate: can not stat () `/var/lib/mlocate/mlocate.db': 没有那个文件或目录

安装好 mlocate 包后,运行 locate 命令会报错,这是因为系统还没有生成那个文件列表库。可以使用 updatedb 命令立即生成更新这个库。如果服务器正跑着业务,最好不要运行这个命令,因为此时服务器压力会很大。这个数据库默认一周更新一次。当使用 locate 命令去搜索一个文件,而该文件正好是在两次更新时间段内创建的,那肯定得不到结果。可以到/etc/updated.conf 去配置这个数据库更新的规则。

locate 所搜索到的文件列表,不管是目录名还是文件名,只要包含我们要搜索的关键词,都会列出来,所以 locate 不适合精准搜索。

使用 find 搜索文件

语法 find [路径] [参数]

-atime +n/-n:访问或执行时间大于/小于 n 天的文件

-ctime +n/-n:写入、更改 inode 属性(例如更改所有者、权限或者链接)时间大于/小于 n 天的文件

-mtime +n/-n:写入时间大于/小于 n 天的文件

[root@localhost ~]# find /tmp/ -mtime -1
/tmp/
/tmp/.ICE-unix
[root@localhost ~]# find /tmp/ -atime +10
[root@localhost ~]# find /tmp/ -atime -1
/tmp/
/tmp/yum.log
/tmp/.ICE-unix

find 常用选项:

-name filename 直接查找该文件名的文件

[root@localhost ~]# find . -name test2
./test2
./test/test2

-type filetype 通过文件类型查找。filetype 包含了 f、b、c、d、l、s 等。

[root@localhost ~]# find /tmp/ -type d
/tmp/
/tmp/.ICE-unix
[root@localhost ~]# find /tmp/ -type f
/tmp/yum.log

find -perm 用法 (http://www.cnblogs.com/hopeworld/archive/2011/04/08/2009252.html

在 windows 中可以在某些路径中查找文件,也可以设定不在某些路径中查找文件,下面用 Linux 中的 find 命令结合其 -path -prune 参数来实现此功能。

假如在当前目录下查找文件,且当前目录下有很多文件及目录(多层目录),包括 dir0 , dir1 和 dir2 等目录及 dir00 , dir01 ...dir10 ,dir11 ...等子目录。

1.在当前目录下查找所有 txt 后缀文件

find ./ -name *.txt

2.在当前目录下的 dir0 目录及子目录下查找 txt 后缀文件

find ./ -path './dir0*' -name *.txt

3.在当前目录下的 dir0 目录下的子目录 dir00 及其子目录下查找 txt 后缀文件

find ./ -path 'dir00' -name *.txt

4.在除 dir0 及子目录以外的目录下查找 txt 后缀文件

find ./ -path './dir0*' -a -prune -o -name *.txt -print

说明: -a 应该是 and 的缩写,意思是逻辑运算符’或‘(&&);-o 应该是 or 的缩写,意思是逻辑运算符’与‘(||), -not 表示非。

命令行的意思是:如果目录 dir0 存在(即-a 左边为真),则求-prune 的值, -prune 返回真,与逻辑表达式为真(即 -path './dir0*' -a -prune 为真),find 命令将在出这个目录以外的目录下查找 txt 后缀文件并打印出来;如果目录 dir0 不存在(即-a 左边为假),则不求 -prune 值,与逻辑表达式为假,则在当前目录下查找所有 txt 后缀文件。

5.在除 dir0、dir1 及子目录以外的目录下查找 txt 后缀文件

find ./ \( -path './dir0*' -o -path './dir1*' \) -a -prune -o -name *.txt -print

注意:圆括号()表示表达式的结合。即指示 shell 不对后面的字符作特殊解释,而留给 find 命令去解释其意义。由于命令行不能直接使用圆括号,所以需要用反斜杠''进行转意(即''转意字符使命令行认识圆括号)。同时注意'(',')'两边都需空格。

6.在 dir0、dir1 及子目录下查找 txt 后缀文件

find ./ \( -path './dir0*' -o -path './dir1*' \) -a -name *.txt -print
  1. 在所有以名为 dir_general 的目录下查找 txt 后缀文件
find ./ -path '/dir_general/' -name *.txt -print

标题:find 搜索命令
作者:散宜生
地址:https://17kblog.com/articles/2016/05/29/1464525118592.html