【问题标题】:How to remove all folders except a few mentioned one in linux如何在linux中删除除少数提到的文件夹之外的所有文件夹
【发布时间】:2016-12-10 10:08:32
【问题描述】:

我的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 文件夹及其内容。

另外,作为删除命令,任何人都可以告诉我是否有办法运行计数命令来查看查询是否选择了正确数量的文件夹?我不想不小心删除任何重要的东西。

谢谢。

【问题讨论】:

标签: linux unix rm


【解决方案1】:

打印树

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

【讨论】:

  • 嗨,我有一个问题。如果我想排除更多文件夹,比如我想排除以下这些文件夹及其中的所有内容:2016/ 2015/, 2014/, nginx-helper/, wpseo-redirects/, gravity_forms/ 如何编辑上述命令以满足我的需要?如我所见,您只排除以20 开头的文件夹。感谢您的帮助。
  • 只需向 grep 添加更多正则表达式,第一个 20\d{2} 匹配所有年份 2000-2099 find . -type d | grep -Pv '(20\d{2}|nginx|wpseo)' | tail -n +2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
  • 1970-01-01
  • 2019-01-03
  • 1970-01-01
  • 1970-01-01
  • 2017-07-01
  • 2021-11-20
相关资源
最近更新 更多