Advertisement
gpulover

rm-invalid-filenames.sh

Sep 15th, 2024
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.42 KB | Source Code | 0 0
  1. #!/bin/bash
  2. #
  3. # This script removes all files with filenames containing non-alphanumeric characters.
  4. # I created it specially for removing files with russian characters for creating an
  5. # OpenBOR pak file.
  6.  
  7. # Set a flag to indicate dry-run mode
  8. dry_run=false
  9.  
  10. # Check for the --dry-run argument
  11. if [[ "$1" == "--dry-run" ]]; then
  12.   dry_run=true
  13. fi
  14.  
  15. # Function to process a directory (and its subdirectories recursively)
  16. process_directory() {
  17.   local dir="$1"
  18.  
  19.   # Loop through all files and subdirectories in the given directory
  20.   for item in "$dir"/*; do
  21.     # Check if the item is a directory
  22.     if [[ -d "$item" ]]; then
  23.       # Extract the directory name
  24.       dirname=$(basename "$item")
  25.  
  26.       # Check if the directory name contains invalid characters
  27.       if [[ "$dirname" =~ [^a-zA-Z0-9_.-] ]]; then
  28.         # Print the directory name
  29.         echo "Invalid directory name: $item"
  30.  
  31.         # Delete the directory and its contents if not in dry-run mode
  32.         if ! $dry_run; then
  33.           rm -rf "$item"
  34.         fi
  35.       else
  36.         # Recursively process the subdirectory
  37.         process_directory "$item"
  38.       fi
  39.     else
  40.       # If it's a file, process it as before
  41.       filename=$(basename "$item")
  42.       if [[ "$filename" =~ [^a-zA-Z0-9_.-] ]]; then
  43.         echo "Invalid filename: $item"
  44.         if ! $dry_run; then
  45.           rm "$item"
  46.         fi
  47.       fi
  48.     fi
  49.   done
  50. }
  51.  
  52. # Start processing from the current directory
  53. process_directory "."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement