find命令总结

时间:2023-03-10 04:16:40
find命令总结

find命令

2018-2-27日整理完成

1,结合-exec的用法

查当前目录下的所有普通文件,并在 -exec 选项中使用ls -l命令将它们列出
# find . -type f -exec ls -l {} \;
-rw-r–r– 1 root root 34928 2003-02-25 ./conf/httpd.conf
-rw-r–r– 1 root root 12959 2003-02-25 ./conf/magic
-rw-r–r– 1 root root 180 2003-02-25 ./conf.d/README

在 /logs 目录中查找更改时间在5日以前的文件并删除它们:
$ find /logs -type f -mtime +5 -exec rm -f {} \;

查询当天修改过的文件
$ find . -mtime -1 -type f -exec ls -l {} \;

2,结合awk的用法:查询并交给awk去处理
 who | awk ’{print $1"\t"$2}’
cnscn pts/0

 df -k | awk ‘{print $1}’ | grep -v ’none’ | sed s"/\/dev\///g"
文件系统
sda2
sda1

3,多级查找

在/tmp中查找所有的*.h,并在这些文件中查找“SYSCALL_VECTOR",最后打印出所有包含"SYSCALL_VECTOR"的文件名

A) find /tmp -name "*.h" | xargs -n50 grep SYSCALL_VECTOR
B) grep SYSCALL_VECTOR /tmp/*.h | cut -d’:' -f1| uniq > filename
C) find /tmp -name "*.h" -exec grep "SYSCALL_VECTOR" {} \; -print

4,查找文件后删除

find / -name filename -exec rm -rf {} \;

5,查找磁盘中大于3M的文件显示出来:
find . -size +3000k -exec ls -ld {} ;

6,将find出来的东西拷到另一个地方
find /etc/ -type f -size -1M -exec cp {} /tmp \; (注意:单位M必须是大写的)

如果有特殊文件,可以用cpio,也可以用这样的语法:
find dir -name filename -print | cpio -pdv newdir

7,查找2004-11-30 16:36:37时更改过的文件
# A=`find ./ -name "*php"` | ls -l –full-time $A 2>/dev/null | grep "2004-11-30 16:36:37"

Linux-all, Linux | No Comments »

注意:之所以find . -name filename |rm -rf不通过,是因为rm命令不接受从标准输入传过来的指令
所以:只能是find . -name filename |xargs rm -rf

8,按名字查找

在当前目录及子目录中,查找大写字母开头的txt文件

[root@localhost ~]# find . -name '[A-Z]*.txt' -print (-print 是打印的意思,可省略,默认就具有 -print 的功能)

在/etc及其子目录中,查找host开头的文件
[root@localhost ~]# find /etc -name 'host*' -print

/etc/hosts
/etc/hosts.allow
/etc/host.conf
/etc/hosts.deny

在$HOME目录及其子目录中,查找所有文件
[root@localhost ~]# find ~ -name '*'

在当前目录及子目录中,查找不是out开头的txt文件
[root@localhost .code]# find . -name "out*" -prune -o -name "*.txt"

在当前目录及子目录中,查找属主具有读写执行,其他具有读执行权限的文件
[root@localhost ~]# find . -perm 755 -print

9,按类型查找
在当前目录及子目录下,查找符号链接文件 (-print可以省略)
find . -type l 
find . -type f -user chen

10,按属主及属组
查找属主是www的文件
 find / -type f -user www

查找属组mysql的文件
[root@localhost .code]# find / -type f -group mysql

11、按时间查找
查找2天内被更改过的文件

find . -type f -mtime -2

查找2天前被更改过的文件
 find . -type f -mtime +2

查找一天内被访问的文件
 find .  -type f -atime -1

查找一天前被访问的文件
 find . -atime +1 -type f

查找一天内状态被改变的文件
 find . -ctime -1 -type f

查找一天前状态被改变的文件
 find . -ctime +1 -type f

查找10分钟以前状态被改变的文件
 find . -cmin +10 -type f

查找比aa.txt新的文件
 find . -newer "aa.txt" -type f

查找比aa.txt旧的文件
 find . ! -newer "aa.txt" -type f

查找比aa.txt新,比bb.txt旧的文件
 find . -newer 'aa.txt' ! -newer 'bb.txt' -type f

查询大于1M的文件
 find / -size +1M -type f

查找等于6字节的文件
 find . -size 6c

查找小于32k的文件
 find . -size -32k

执行命令
查找del.txt并删除,删除前提示确认
 find . -name 'del.txt'  -exec rm -f {} \;

查找aa.txt 并备份为aa.txt.bak
 find . -name 'aa.txt' -exec cp {} {}.bak \;

查找aa.txt 归档压缩为aa.txt.tar.gz 并删除aa.txt
find . -name "aa.txt" -type f -exec tar -zcvf {}.tar.gz {} \; -exec rm -rf {} \; > /dev/null