【问题标题】:Delete recursively files in a folder and in child folder [duplicate]递归删除文件夹和子文件夹中的文件[重复]
【发布时间】:2019-07-02 21:16:22
【问题描述】:

我想在不删除文件夹的情况下递归删除文件夹及其子文件夹中包含的所有文件。

例如我有这个结构:

MainFolder
│   Somefile6
│   Somefile7
│ 
└───child1
│   |   Somefile
│   |   Somefile2
│   │   
│   └───child2  
│       │   Somefile3
│       │   Somefile4
│       │
│       └───child3
│           │   Somefile5

运行 bash 脚本后(我尝试过):

#!/bin/bash
shopt -s nullglob dotglob # Include hidden file
dir=(/root/some/path/*)
if [ ${#dir[@]} -gt 0 ]; then
    for file in "$dir"
    do
        echo "Doing some custom action before deleting..."
        echo "Deleting $file"
        rm "$file"
        sleep 1
    done
else
    echo "The folder is empty";
fi

我期望得到什么

MainFolder
│ 
└───child1
│   │   
│   └───child2  
│       │
│       └───child3
│           │   

问题:

只是删除文件Somefile6Somefile7

【问题讨论】:

  • 因为这是你告诉它的。 for file in "$dir".
  • 如何解析所有文件夹? @Robert 您标记的重复答案没有回答我的问题

标签: bash shell


【解决方案1】:

您可以使用find 查找所有文件并将其删除:

find -type f -delete
  • -type f:告诉find 只生成文件
  • -delete:告诉find 删除所有找到的项目

如果您不想删除文件,您可以使用-exec 并对文件find 执行任何您想要的操作。

【讨论】:

  • 我知道但是我需要以递归的方式使用它,因为我要在删除之前做一些操作
  • 如果您想做其他事情,只需使用-exec 而不是-delete。我已经更新了帖子。
  • 我可以在 exec 中使用条件吗?
  • 如果您要执行的代码更复杂 - 只需传递一个脚本。
  • export -f somefunc; find . -exec bash -c 'somefunc "$0"' {} ` Here it'll execute somefunc` 您需要在我们的脚本中定义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
  • 1970-01-01
  • 2018-11-09
  • 2012-11-19
  • 1970-01-01
相关资源
最近更新 更多