如何删除除linux中提到的几个文件夹之外的所有文件夹

时间:2016-12-10 10:08:33

标签: linux unix rm

我的wp-content文件夹=>

中有以下文件夹结构
2016/ => it has many subfolders in it and I wanna keep them
2015/ => it has many subfolders in it and I wanna keep them
2014/ => it has many subfolders in it and I wanna keep them
2013/ => it has many subfolders in it and I wanna keep them

besides those folder there are tons of temp folders which I want to delete along with anything inside it. The folder name look like this:

ZhsvhgTjh/
Vgfsugu79/
1agDjgdki/
8gdygREfh/
Hbjddsyug/
....so on....

现在的问题是,如果我运行rm -f,那么它将删除该文件夹中的所有内容,包括2016, 2015, 2014, 2013等文件夹。

此外,如果我尝试以下操作:find . -name a -exec rm -rf {} \;那么它只适用于1个文件夹名称,我输入的每个随机文件夹名称都是疯狂的,因为它有超过20,000个临时文件夹。

所以,我希望是否有人可以帮助我使用一个命令,除了2016, 2015, 2014, 2013文件夹及其内容之外,我可以删除其中的所有文件夹和内容。

此外,如果有一种方法我可以运行计数命令来查看查询是否选择了正确数量的文件夹,那么任何人都可以告诉我吗?我不想意外删除任何重要的东西。

谢谢。

1 个答案:

答案 0 :(得分:2)

打印树

prodrive11@raccoon:~/tmpp/wp-content$ ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'
   .
   |-2015
   |---keep2
   |---keep3
   |-2016
   |---keep1
   |---keep2
   |-NKAXOIND
   |-x232sfsw
   |---we233ds

显示垃圾文件夹:

   prodrive11@raccoon:~/tmpp/wp-content$ find . -type d | grep -Pv '20\d{2}' | tail -n +2                   ./x232sfsw
    ./x232sfsw/we233ds
    ./NKAXOIND

算他们

prodrive11@raccoon:~/tmpp/wp-content$ find . -type d | grep -Pv '20\d{2}' | tail -n +2 | wc -l
3

删除它们

prodrive11@raccoon:~/tmpp/wp-content$ find . -type d | grep -Pv '20\d{2}' | tail -n +2 | xargs rm -rf

再次显示树

prodrive11@raccoon:~/tmpp/wp-content$ ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'
   .
   |-2015
   |---keep2
   |---keep3
   |-2016
   |---keep1
   |---keep2