問題:刪除一個目錄下的所有文件,但保留一個指定文件
方法一:
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"
`
從運維角度,任何刪除性的操作都應該事先備份後在執行或者確認有備份存在。