刪除乙個目錄下的所有檔案,但保留乙個指定文

2021-07-03 02:53:19 字數 2927 閱讀 9885

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

面試題:刪除乙個目錄下的所有檔案,但保留乙個指定檔案

解答:

假設這個目錄是/xx/,裡面有file1,file2,file3..file10  十個檔案

[root@oldboy xx]# touch file

[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

老男孩老師點評:此法沒啥用,講出來反而會讓人覺得你水平不行,一看就是搜尋出來的,但是作為知識研習是可以的!此法面試答出來有可能是減分項!

從運維角度,任何刪除性的操作都應該事先備份後在執行或者確認有備份存在。

刪除乙個目錄下的所有檔案但保留乙個指定檔案

之前看過oldboy 老男孩 前輩的一篇文章 linux面試題 刪除乙個目錄下的所有檔案,但保留乙個指定檔案 近日終於有機會得以驗證,但與老男孩前輩的文章中具體講的有些不太一樣,故而專門寫一篇文章重新整理這個問題。雖然是同乙個話題,和同一種思路,但細節上有一定的差別。需求 刪除乙個目錄下的所有檔案,...

C 刪除乙個檔案目錄下的所有檔案以及目錄

bool doremovedirectory cstring chrdirname bool releasedirectory cstring chrdirname end of civmsvrinfo releasedirectory bool doremovedirectory cstring ...

VC 刪除乙個檔案目錄下的所有檔案以及目錄

1 bool doremovedirectory cstring chrdirname 23 bool releasedirectory cstring chrdirname 4 end of civmsvrinfo releasedirectory 1415 bool doremovedirect...