削除スクリプト

#!/bin/bash 
 
# Directory to search for matching directories 
search_directory="path_to_the_target_dir" 
 
# Define the range of the last three digits for deletion 
min_number=30 
max_number=31 
 
# Prefix to match in directory names 
prefix="prefix_to_delete" 
 
# Create an array to store directories to delete 
to_delete=() 
 
# Function to search for directories to delete 
search_for_delete() { 
    for dir in "$search_directory"/*; do 
        if [[ -d "$dir" ]]; then 
            # Extract the directory name from the path 
            dir_name="${dir##*/}" 
                
            # Define a regular expression pattern to match the directory name 
            pattern="${prefix//./\\.}\\.[0-9]{3}$" # Include a dot and exactly three digits after prefix 
 
            # Check if the directory name matches the pattern  
            if [[ "$dir_name" =~ $pattern ]]; then 
                # Extract the last three digits after the prefix 
                last_three_digits="${dir_name#"$prefix."}" 
 
                # Convert last_three_digits to an integer (force decimal interpretation) 
                last_three_digits_int=$((10#${last_three_digits})) 
                        
                # Check if it's a valid number 
                if [[ "$last_three_digits_int" =~ ^[0-9]+$ ]]; then 
                    # Check if the digits are within the specified range 
                    if ((last_three_digits_int >= min_number && last_three_digits_int <= max_number)); then 
                        to_delete+=("$dir_name") 
                    fi      
                fi      
                
            fi       
        fi       
    done    
} 
 
# Function to delete directories in the to_delete array 
delete_directories() { 
    for dir_name in "${to_delete[@]}"; do 
        dir_path="$search_directory/$dir_name" 
        echo "Directory to delete: $dir_name" 
    done     
 
    read -p "Delete the above directories? (Y/N): " choice 
    if [[ $choice == "Y" || $choice == "y" ]]; then 
        for dir_name in "${to_delete[@]}"; do 
            dir_path="$search_directory/$dir_name" 
            rm -r "$dir_path" 
            echo "Deleted directory $dir_name." 
        done     
    else     
        echo "Deletion canceled." 
    fi 
} 
 
# Main execution 
echo "Searching for directories within the specified range..." 
 
search_for_delete 
 
if [ ${#to_delete[@]} -eq 0 ]; then  
    echo "No directories found to delete." 
else 
    echo "The following directories are within the specified range and have the prefix '$prefix':" 
    for dir_name in "${to_delete[@]}"; do 
        echo "$dir_name" 
    done     
    delete_directories 
fi

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA