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 {} \;
使用xargs:
find ./ -type f -mtime +3 |xargs rm -rf {} \;
find ./ -type f -mtime +3 |xargs rm -rf