面試題:刪除一個目錄下的全部文件,但保留一個指定文件 解答: 假設這個目錄是/xx/,裏面有file1,file2,file3..file10 十個文件 [root@oldboy xx]# touch file{1..10} [root@oldboy xx]# ls file1 file10 file2 file3 file4 file5 file6 file7 file8 file9 方法一: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吧 #感謝兩位熱心師兄還有老男孩老師的熱心解答 C組副組長--張耀 北京-吳曉宇 老男孩老師點評:此法最佳!必會方法! 方法二: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 第三種方法一樣感謝熱心的師兄 北京-張重生Net 老男孩老師點評:此法沒啥用,講出來反而會讓人以爲你水平不行,一看就是搜索出來的,可是做爲知識研習是能夠的!此法面試答出來有多是減分項! 原文地址:http://oldboy.blog.51cto.com/2561410/1650380