Linux文件查找:
locate: 非实时查找,根据数据库(速度快);模糊查找;
find:实时查找,精确匹配;速度慢;
find [查找位置] [查找标准] [处理动作]
查找位置:默认为当前目录;
查找标准:默认为查找指定目录下的所有文件;
处理动作:显示到标准输出;
查找标准:
-name "文件名称": 根据文件名查找,精确查找文件。
支持glob, *, [], ?
-iname "文件名称":根据文件名查找,不区分字符大小写;name ignore case
-user USERNAME: 根据属主查找;
-group GRPNAME: 根据属组查找;
-uid UID; #按照Uid 来查找
-gid GID; #按照gid来查找
-nouser:查找没属主的文件;
-nogroup: 查找没有属组的文件;
组合查找条件:
-a: 与
-o:或
-not, !: 非
例如:查找/tmp目录下没有属主,并且文件名以一个字符.test文件;
# find /tmp -name "?.test" -nouser -ls
-type
f: 普通文件
d: 目录
b: 块设备
c: 字符设备
l: 符号链接
p: 命名管道
s: 套接字文件
-size
12MB (11.,12)MB #表示精确12MB 大小 查找
-size [+|-]2MB #+表示大于2MB -表示小于2MB
常用单位:
k
M
G
根据时间来查找:
time的时间单位是day 天
-atime [+|-]# 访问时间 access time
-atime 3#表示刚好在过去第3天访问过的文件
-atime -3#表示3天以内访问的文件
-atime +3#表示至少3天没有访问的文件
-mtime [+|-]# 修改时间 modify time
-ctime [+|-]# 改变时间 change time
min的时间单位是minute 分钟
-amin [+|-]
-amin 3#表示刚好在过去第3分钟访问过的文件
-amin -3#表示3分钟以内访问的文件
-amin +3#表示至少3分钟没有访问的文件
-mmin [+|-]
-cmin [+|-]
根据权限查找:
-perm [+|-]MODE
没有[+|-]表示精确权限匹配;
+MODE: 任何一类用户的任何一位权限匹配即可;
-MODE: 每类用户的每位权限都匹配;
处理动作:
-print: 显示
-ls: 显示查找到的文件的详细信息;
-exec COMMAND \; #执行操作
find /tmp -atime +30 -exec mv {} {}.old \; #用到文件名的时候用花括号,{} 表示原来的文件名,{}.old 在原来文件名后面加上.old
-ok COMMAND \;
练习:
1、查找/var目录下属主为root并且属组为mail的所有文件;
find /var -user root -group mail
2、查找/usr目录下不属于root,bin,或student的文件;
find /usr -not \( -user root -o -user bin -o -user student \)
find /usr -not -user root -a -not -user bin -a -not -user student
3、查找/etc目录下最近一周内内容修改过且不属于root及student用户的文件;
find /etc -mtime -7 -a -not -user root -a -not -user student
find /etc -mtime -7 -a -not \( -user root -o -user student \)
4、查找当前系统上没有属主或属组且最近1天内曾被访问过的文件,并将其属主属组均修改为root;
find / \( -nouser -o -nogroup \) -a -atime -1 -exec chown root:root {} \;
5、查找/etc目录下大于1M的文件,并将其文件名写入/tmp/etc.largefiles文件中;
find /etc -size +1M -exec echo {} >> /tmp/etc.largefiles \;
find /etc -size +1M >> /tmp/etc.largefiles
6、查找/etc目录下所有用户都没有写权限的文件,显示出其详细信息;
find /etc -not -perm +222
find / \( -nouser -o -nogroup \) -a -atime -1 | xargs -i chown root:root {}
类型不是目录,而且没有属主的文件;
find / -not -type d -a -nouser -exec rm -f {} \;
find / -not -type d -a -nouser | xargs -i rm -f {} #xargs 表示可以执行命令,可以从前面的命令传入所需的文件名也是用{}来调用。只不过调用需要用-i 选项。
find / -size +10M -a -atime +10 -exec mv {} {}.old \;
本文出自 “技术成就梦想” 博客,请务必保留此出处http://zkw9527.blog.51cto.com/1346897/1318788