1、如圖所示,有大量文件夾,想批量刪除它們
2、使用命令 find . -maxdepth 1 -regex ".*ws.*" 可以批量找到他們。maxdepth值為1表示只在當前目錄查找,不遞歸查找其子目錄
3、使用命令 find . -maxdepth 1 -regex ".*ws.*" -exec rm -rf {} \; 批量刪除它們,這個世界瞬間清爽了很多
ps注意后面的分號,不要省略啊
4、使用命令 find . -maxdepth 1 -regex ".*ws.*" | xargs rm -rf 同樣可以批量刪除
xargs是把前面的輸出作為后面的參數,如果多行輸出,就多次執行后面的命令
5、有的linux系統支持的regex正則表達式不一樣,可以使用下面的方式替換
find . -maxdepth 1 -name "*ws*" | xargs rm -rf
6、find使用正則:
find . -regex ".*\.\(txt\|sh\)"
加參數“-regextype type”可以指定“type”類型的正則語法,find支持的正則語法有:valid types are `findutils-default', `awk', `egrep', `ed', `emacs', `gnu-awk', `grep', `posix-awk', `posix-basic', `posix-egrep', `posix-extended', `posix-minimal-basic', `sed'.
顯示20分鍾前的文件
find /home/prestat/bills/test -type f -mmin +20 -exec ls -l {} \;
find /home/prestat/bills/test -type f -mmin +20 -exec ls -l {} +
刪除20分鍾前的文件
find /home/prestat/bills/test -type f -mmin +20 -exec rm {} \;
顯示20天前的目錄
find /home/prestat/bills/test -type d -mtime +20 -exec ls -l {} \;
刪除20天前的目錄
find /home/prestat/bills/test -type d -mtime +20 -exec rm {} \;
在20-50天內修改過的文件
find ./ -mtime +20 -a -mtime -50 -type f
排除某些目錄:
find ${JENKINS_HOME}/jobs -maxdepth 1 -name "*" -mtime +60 ! -path /var/lib/jenkins/jobs | xargs ls -ld;
排除某些文件:
find ${JENKINS_HOME}/jobs -maxdepth 1 ! -name "*.xml" -mtime +60 ! -path /var/lib/jenkins/jobs | xargs ls -ld;
理解下兩種寫法的區別:對結果沒有影響;{}表示find找到的列表
find . -exec grep chrome {} \;
or
find . -exec grep chrome {} +
find
will execute grep
and will substitute {}
with the filename(s) found. The difference between ;
and +
is that with ;
a single grep
command for each file is executed whereas with +
as many files as possible are given as parameters to grep
at once.
find . -type f | while read f; do echo $f; # do something done
另外,可以使用-ok替換-exec操作:-ok相比-exec多了提示的功能,每一步都需要用戶確認,這樣對於rm操作,更加安全
舉例:找出內容為空的文件刪除
參考:
https://javawind.net/p132
http://man.linuxde.net/find
https://unix.stackexchange.com/questions/12902/how-to-run-find-exec