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


此題問題雖小,但是初學者還是很難給出合理的答案的!本文來自老男孩21期網絡班學員

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
48
49
50
51
52
53
54
面試題:刪除一個目錄下的所有文件,但保留一個指定文件
 
解答:
假設這個目錄是 /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" `
 
從運維角度,任何刪除性的操作都應該事先備份后在執行或者確認有備份存在。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM