Bash 删除包含某些文件的目录

Bash delete directories containing certain files

给定一个像

这样的目录结构
parent
  - child1
    - file1
    - file2
    - file3
  - child2
    - file1
    - file3
  - child3
    - file1
    - file2
    - file3
    - file4

什么命令将删除 parent 的所有子目录,这些子目录包含 file1file2file3 的全部或部分内容,但不包含其他内容。 IE。在示例中 child1child2 应该删除,但 child3 应该保留,因为它还包含 file4.

请post命令的干运行和实际版本首先检查哪些文件夹将被删除。

我想这就是你想要的?循环遍历父目录中的文件,如果生成的文件路径不包含 file4

则删除它们

这显示了将要删除的文件

while IFS= read -r -d $'[=10=]' f; do
  if [[ "$f" =~ 'file4' ]]; then
    continue;
  else
    echo "rm "$f""
  fi
done < <(find parent -type f -print0)

这将删除它们

while IFS= read -r -d $'[=11=]' f; do
  if [[ "$f" =~ 'file4' ]]; then
    continue;
  else
    rm "$f"
  fi
done < <(find parent -type f -print0)

假设父目录只包含子文件夹,这一行将列出仅包含标记为删除列表中的文件的文件夹:

for child in *; do if [ "$(ls -1 $child | egrep -v '(file1|file2|file3)'|wc -l)" -eq "0" ]; then echo "would delete $child"; fi ; done

这一行命令将删除它们:

for child in *; do if [ "$(ls -1 $child | egrep -v '(file1|file2|file3)'|wc -l)" -eq "0" ]; then rm -rf $child; fi ; done

您可能需要一个仅在子目录不包含您要检查的输入文件集时才删除子目录的功能。

#!/bin/bash
delete_dir() {
    local subdir=
    local string_of_files=

    #convert list of files into array
    IFS=','
    read -ra files_to_keep <<< "$string_of_files"

    local list_of_files=()
    if [ -d "$subdir" ]; then
        for i in $subdir/*; do list_of_files=("${list_of_files[@]}" $(basename $i)); done

        local list_of_matched_files=()
        for i in ${list_of_files[@]}; do
            if [[ " ${files_to_keep[@]} " =~ " $i " ]]; then
               list_of_matched_files=("${list_of_matched_files[@]}" "$i")
            fi
        done

        if [ "${#list_of_matched_files[@]}" -eq 0 ]; then
            echo "deleting $subdir"
            #rm -r $subdir
        else
            echo "Not deleting $subdir, since it contains files you want to keep!!"
        fi
    else
        echo "directory $subdir not found"
    fi
    }

# Example1: function call
delete_dir child1 file4

# Example2: For your case you can loop through subdirectories like,
for dir in $(ls -d parent/child*); do
    delete_dir $dir file4
done

示例输出:

$ ./test.sh
Not deleting child1/, since it contains files you want to keep!!
Not deleting child2/, since it contains files you want to keep!!
deleting child3/

如果您可以自由选择,最好使用 python 进行此类操作,因为这样可以使操作更加简单和模块化。