Linux:刪除一個目錄下的所有文件,但保留一個指定文件
面試題:刪除一個目錄下的所有文件,但保留一個指定文件
解答:
假設這個目錄是
/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
老男孩老師點評:此法沒啥用,講出來反而會讓人覺得你水平不行,一看就是搜索出來的,但是作為知識研習是可以的!此法面試答出來有可能是減分項!
再補充兩種方法(20150802 來自老男孩教育25期課堂)
方法四:
find
./ -
type
f|
grep
-
v
"\boldboy1\b"
|
xargs
rm
-f
方法五:
rm
-f `
ls
|
grep
-
v
"\boldboy1\b"
`
從運維角度,任何刪除性的操作都應該事先備份后在執行或者確認有備份存在。