linux中刪除一個目錄下的所有文件,但保留一個指定文件

問題:刪除一個目錄下的所有文件,但保留一個指定文件

方法一:find
[root@oldboy xx]# ls
file1  file10  file2  file3  file4  file5  file6  file7  file8  file9
[root@oldboy xx]# find /xx -type f ! -name "file10"|xargs rm -f 
[root@oldboy xx]# ls
file10
 
[root@oldboy xx]# find /xx -type f ! -name "file10" -exec rm -f {} \;     
[root@oldboy xx]# ls
file10
 
這兩種一個通過xargs傳參,一個通過find的-exec執行命令參數來完成,都算作find

 
點評:此法最佳!必會方法!
 
 
 
方法二:rsync
[root@oldboy xx]# ls
file1  file10  file2  file3  file4  file5  file6  file7  file8  file9
[root@oldboy xx]# rsync -az --delete --exclude "file10" /null/ /xx/
[root@oldboy xx]# ls
file10
 
點評:此法爲錦上添花,加分項!
 
 
方法三:開啓bash的extglob功能(此功能的作用就是用rm !(*jpg)這樣的方式來刪除不包括號內文件的文件)
[root@oldboy xx]# shopt -s extglob
[root@oldboy xx]# ls
file1  file10  file2  file3  file4  file5  file6  file7  file8  file9
[root@oldboy xx]# rm -f !(file10)
[root@oldboy xx]# ls
file10
第三種方法
點評:此法沒啥用,講出來反而會讓人覺得你水平不行,一看就是搜索出來的,但是作爲知識研習是可以的!此法面試答出來有可能是減分項!
 

方法四:
find ./ -type f|grep -v "\boldboy1\b"|xargs rm -f
 
方法五:
rm -f `ls|grep -v "\boldboy1\b"`
 
從運維角度,任何刪除性的操作都應該事先備份後在執行或者確認有備份存在。



發佈了19 篇原創文章 · 獲贊 6 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章