find 命令:查找文件

find命令用于查找文件,其命令格式为:

find  [起始目录]  [搜索条件]  [操作]

其中[起始目录]是指命令将从该目录起,遍历其下的所有子目录,查找满足条件的文件。该目录默认是当前目录。[搜索条件]是一个逻辑表达式,当表达式为”真”时,搜索条件成立,为”假”时不成立。搜索条件的一般表达式及其说明见表6.20。表6.20  find命令搜索条件的一般表达式及其说明

搜索条件 说    明
-name ‘字符串’ 查找文件名中包含所给字符串的所有文件
-user ‘用户名’ 查找属于指定用户的文件
-group ‘用户组名’ 查找属于指定用户组的文件
-type x 查找类型为x的文件,类型包括b(块设备文件),c(字符设备文件), d(目录文件),p(命名管道文件), f(普通文件),l(符号链接文件), s(socket文件)
-atime n 查找n天以前被访问过的文件
-size n 指定文件大小为n
-perm 查找符合指定权限值的文件或目录
-mount 要查找文件时不跨越文件系统mount点
-follow 如果find命令遇到符号链接文件,就跟踪到链接所指向的文件
-cpio 对匹配的文件使用cpio命令,将文件备份到磁带设备中
-newer file1 ! file2 查找更改时间比文件file1晚但比文件file2早的文件
-prume 不在指定的目录中查找,如果同时指定-depth选项,那么-prune将被 find命令忽略
-ok 和exec作用相同,但在执行每一个命令之前,都会给出提示,由用户来确定是否执行
-depth 在查找文件时,首先查找当前目录,然后再在其他子目录中查找
-exec 命令名 {} ; 不需确认执行命令。注意: “{}”代表找到的文件名,“}”与“”之间有空格
-print 送往标准输出
例如从当前目录查找所有以.txt结尾的文件并在屏幕上显示出来,命令行为:
find  .  -name  '*.txt'   -print

查找两个后缀的文件,就改为下面的用法:
find . ( -name *.xml -o -name *.sh )

再如从根目录查找类型为符号连接的文件,并将其删除,命令行为:
find  /  -type  l  -exec  rm {} ;

只查找文件,不包含目录的(该行,不能加--print,加了会报错):
find  . -type f

又如从当前目录查找用户tom的所有文件并在屏幕上显示,命令行为:
find  .  -user  'tom'   -print

又如显示当前目录中大于20字节的.c文件名,命令行为:
find  . -name  "*.c"  -size  +20c  -print

显示当前目录中恰好10天前访问过的文件名,命令行为:
find  .  -atime  10  -print

显示当前目录中不到10天前访问过的文件名,命令行为:
find  .  -atime  -10  -print

查找/home目录下权限为640的文件或目录,命令行为:
find  /home  -perm 640

搜索根目录下大于100KB的文件,并显示,命令行为:
find  /  -size  +100K  -print

搜索根目录下小于500KB的文件,命令行为:
find  /  -size  -500K  -print

删除文件大小为0的文件
rm -i `find ./ -size 0`
find ./size 0 exec rm {} ;
find ./size 0|xargs rm -rf
在当前目录中查找所有文件名以.doc结尾,且更改时间在5天以上的文件,找到后进行删除,且删除前给出提示,命令行为:
find  .  -name  '*.doc'  -mtime +5  -ok  rm {} ;或
find . -mtime +5 -name "*.*" -exec rm -f {} ;  自动删除当前目录五天以前的文件

注:后面的反斜杠不能少,不然会报 ”find: 遗漏”-exec”的参数” 。

在当前目录下查找所有链接文件,并以长格式显示文件的基本信息,命令行为:

# find  .  -type l  -exec  ls  -l {} ;
lrw-rw-r-- 1 root root 36 07-27 14:34 ./example2
lrw-rw-r-- 1 root root 72 07-27 14:36 ./example3
lrw-rw-r-- 1 root root 36 07-27 14:36 ./example1

在当前目录中查找文件名由一个小写字母、一个大写字母和两个数字组成,且扩展名为.doc的文件,并显示,命令行为:
find  .  -name  ' [a-z][A-Z][0-9][0-9].doc'  -print

查找空文件夹:
find -type d -empty

后记:

#Bash find files between two dates:
#Returns a list of files that have timestamps after 2010-10-07 and before 2014-10-08
find . -type f -newermt 2010-10-07 ! -newermt 2014-10-08

#Returns files with timestamps between 2014-10-08 10:17:00 and 2014-10-08 10:53:00
find . -type f -newermt "2014-10-08 10:17:00" ! -newermt "2014-10-08 10:53:00"

#Knowing immediately as files are skipped due to duplicate names:
find srcdir -type f -newermt 2014-08-31 ! -newermt 2014-09-30 -exec mv -n {} destdir/ \; \
    -exec [ -f {} ] \; -exec printf "\`%s' skipped (exists in \`%s')\\n" {} destdir \;

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注