bashfinddelete-directory

Bash delete directories containing certain files


Given a directory structure like

parent
  - child1
    - file1
    - file2
    - file3
  - child2
    - file1
    - file3
  - child3
    - file1
    - file2
    - file3
    - file4

what command will delete all child directories of parent that contain all or some of file1, file2, file3 but no others. I.e. in the example child1 and child2 should be deleted but child3 should remain since it also contains file4.

Please post both a dry run and actual version of the command to first check which folders would be deleted.


Solution

  • You would probably need a function that deletes the child directories only if it does not contain a set of input file(s) you want to check for.

    #!/bin/bash
    delete_dir() {
        local subdir=$1
        local string_of_files=$2
    
        #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
    

    example output:

    $ ./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/
    

    You'd be better off using python for such operations if you're are at liberty to choose, since you can make it much simpler and modular.