linux常用命令

find命令查找出文件后,配合exec参数,可以对查找出的文件进行进一步操作

1. 参数说明

格式:find -type f -mtime +2 -exec ls -l {} ;

-exec参数是以分号为结束标志的;考虑到各个系统中分号有不同的含义,所以前面加反斜杠

{ } 代表前面find查找出来的文件名

大多数用户使用find+exec组合,是为了查找旧文件并删除它们,建议在真正执行rm命令前,先执行ls -l命令查看一下,确认它们是所要删除的文件

2. 使用示例

a)查找当前目录下的文件,并对结果执行ls -l

find ./ -type f -exec ls -l {} ;
[root@localhost zhangyang]# ls
1.txt  kk
[root@localhost zhangyang]# find ./ -type f
./kk/3.txt
./1.txt
[root@localhost zhangyang]# find ./ -type f -exec ls -l {} ;
-rw-r--r--. 1 root root 0 6月   4 09:16 ./kk/3.txt
-rw-r--r--. 1 root root 0 6月   4 09:26 ./1.txt

b)查找当前目录下,名字为2.txt的文件,并删除(删除,没有提示,慎用!)

find ./ -name 2.txt -exec rm -rf {} ;
[root@localhost zhangyang]# ll
总用量 0
-rw-r--r--. 1 root root  0 6月   4 09:26 1.txt
-rw-r--r--. 1 root root  0 6月   4 10:42 2.txt
drwxr-xr-x. 2 root root 19 6月   4 09:16 kk
[root@localhost zhangyang]# 
[root@localhost zhangyang]# find ./ -name 2.txt -exec ls -l {} ;
-rw-r--r--. 1 root root 0 6月   4 10:42 ./2.txt
[root@localhost zhangyang]# find ./ -name 2.txt -exec rm -rf {} ;
[root@localhost zhangyang]# ll
总用量 0
-rw-r--r--. 1 root root  0 6月   4 09:26 1.txt
drwxr-xr-x. 2 root root 19 6月   4 09:16 kk

c)查找当前目录下,名字为2.txt的文件,并删除(删除,有提示)

find ./ -name 2.txt -ok rm -rf {} ;  (-ok是-exec的安全模式)
[root@localhost zhangyang]# ll
总用量 0
-rw-r--r--. 1 root root  0 6月   4 09:26 1.txt
-rw-r--r--. 1 root root  0 6月   4 10:48 2.txt
drwxr-xr-x. 2 root root 19 6月   4 09:16 kk
[root@localhost zhangyang]# find ./ -name 2.txt
./2.txt
[root@localhost zhangyang]# find ./ -name 2.txt -exec ls -l {} ;
-rw-r--r--. 1 root root 0 6月   4 10:48 ./2.txt
[root@localhost zhangyang]# find ./ -name 2.txt -ok ls -l {} ;
< ls ... ./2.txt > ? y
-rw-r--r--. 1 root root 0 6月   4 10:48 ./2.txt
[root@localhost zhangyang]# find ./ -name 2.txt -ok rm -rf {} ;
< rm ... ./2.txt > ? y
[root@localhost zhangyang]# ll
总用量 0
-rw-r--r--. 1 root root  0 6月   4 09:26 1.txt
drwxr-xr-x. 2 root root 19 6月   4 09:16 kk

 d)实际使用中,删除logs文件夹下过期旧日志(删除一天前的日志)

find ./ -type f -mtime +1 -exec ls -l {} ;

find ./ -type f -mtime +1 -ok rm -rf {} ;
原文地址:https://www.cnblogs.com/xiaochongc/p/13042176.html