此題問(wèn)題雖小,但是初學(xué)者還是很難給出合理的答案的!本文來(lái)自老男孩21期網(wǎng)絡(luò)班學(xué)員
面試題:刪除一個(gè)目錄下的所有文件,但保留一個(gè)指定文件
解答:
假設(shè)這個(gè)目錄是/xx/,里面有file1,file2,file3..file10 十個(gè)文件
[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
這兩種一個(gè)通過(guò)xargs傳參,一個(gè)通過(guò)find的-exec執(zhí)行命令參數(shù)來(lái)完成,都算作find吧
點(diǎn)評(píng):此法最佳!必會(huì)方法!
方法二: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
點(diǎn)評(píng):此法為錦上添花,加分項(xiàng)!
方法三:開(kāi)啟bash的extglob功能(此功能的作用就是用rm !(*jpg)這樣的方式來(lái)刪除不包括號(hào)內(nèi)文件的文件)
[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
點(diǎn)評(píng):此法沒(méi)啥用,講出來(lái)反而會(huì)讓人覺(jué)得你水平不行,一看就是搜索出來(lái)的,但是作為知識(shí)研習(xí)是可以的!此法面試答出來(lái)有可能是減分項(xiàng)!
再補(bǔ)充兩種方法
方法四:
find ./ -type f|grep -v "\boldboy1\b"|xargs rm -f
方法五:
rm -f ls|grep -v "\boldboy1\b"
從運(yùn)維角度,任何刪除性的操作都應(yīng)該事先備份后在執(zhí)行或者確認(rèn)有備份存在。