find命令的总结
linux下的find命令在目录结构中搜索文件,并执行指定的操作。
linux下的find命令提供了相当多的查找条件,功能很强大。由于find具有强大的功能,所以它的
选项特别特别多。
在运行一个非常消耗资源的find命令时,很多人都倾向于把它放在后台执行,因为遍历一个大的文
件系统可能会花费很长的时间。
find命令的格式:find [-path...] -options[-print -exec -ok]
path:要查找的目录路径。
~表示¥HOME目录
.表示当前目录
/表示根目录
-print:表示讲结果输出到标准输出
-exec:对匹配的文件执行该参数所给出的shell命令。
形式为command {} \; ({}和\;之间有空格)
-ok:与-exec作用相同,区别在于,在执行命令之前,都会给出提示,让用户确认执行
option常用的选项:
-name按照名字查找
-perm安装权限查找
-prune不再当前指定的目录下查找
-user文件属主来查找
-group所属组来查找
-type按照文件类型来查找
-nouser查找无有效属主的文件
-nogroup查找无有效的所属组的文件
我简单的举两个例子:
一:find -name
扩展几个-name用法
1.在当前目录及子目录中,查找大写字母开头的txt文件
[liang@localhost code]$ find . -name '[a-z]*.txt' -print
2.在/etc及其子目录中,查找host开头的文件
[liang@localhost code]$ find /etc -name 'host*' -print
3.在$HOME目录下及其子目录中,查找所有文件
[liang@localhost ~]$ find ~ -name '*' -print
[liang@localhost ~]$ find . -name "out*" -prune -o -name "*.txt" -print
二.按目录查找
1.在当前目录除了AA之外的子目录内搜索txt文件
[liang@localhost ~]$ find . -path "./aa" -prune -o -name "*.txt" -print
[liang@localhost ~]$ find . -path"./aa" -o-path "./bb" -prune -o -name "*.txt" -print
[liang@localhost ~]$ find . ! -name "." -type d -prune -o -type f -name "*.txt" -print
四.按类型查找
在当前目录及子目录下,查找符号链接文件
[liang@localhost ~]$ find . -type l -print
五.按照属主及属组
查找属主是root的文件:
2.查找属主被删除的文件
[liang@localhost ~]$ find / -nouser -type f -print
3.查找属组liang的文件
[liang@localhost ~]$ find / -group liang -type f -print
4.查找属组被删除的文件
find / -nogroup -type f -print
六.按时间查找
查找2天内被更改过的文件
[liang@localhost ~]$ find . -mtime -2 -type f -print
查找两天前被更改过得文件
[liang@localhost ~]$ find . -mtime +2 -type f -print
查找一天内被访问的文件
[liang@localhost ~]$ find . -atime -1 -type f -print
查找一天前被访问的文件
[liang@localhost ~]$ find . -atime +1 -type f -print
查找10分钟以前状态被改变的文件
[liang@localhost ~]$ find . -cmin +10 -type f -print
七。按文件新旧
1.查找比aa.txt新的文件
[liang@localhost ~]$ find . -newer "aa.txt" -type f -print
[liang@localhost ~]$ find . ! -newer "aa.txt" -type f -print
3.查找比aa.txt新,比bb.txt旧的文件
[liang@localhost ~]$ find . -newer 'aa.txt' ! -newer 'bb.txt' -type f -print
1.查找超过1M的文件
[liang@localhost ~]$ find / -size +1M -type f -print
[liang@localhost ~]$ find . -size 100c -print
[liang@localhost ~]$ find . -size -50k -print
九.执行命令
1.查找del.txt并删除,删除前提示确认
[liang@localhost ~]$ find . -name 'del.txt' -ok rm {} \;
2.查找aa.txt并备份为aa.txt.bak
[liang@localhost ~]$ find . -name 'aa.txt' -exec cp {} {}.bak \;
[liang@localhost ~]$find . -name "aa.txt" -type f -exec tar -zcvf {}.tar.gz {} \; -exec rm -rf {} \; > /dev/null