DEV Community

Alexander6
Alexander6

Posted on

Rename all files and directories in the current folder

This command is created by ChatGPT, it will recursively go through all files and directories in the current directory, change every "Dicexxxx" into "Ringxxxxx"

#!/bin/bash

# Recursive function to handle files and directories
rename_files_and_directories() {
  local dir=$1
  cd "$dir"

  # First handle files
  for file in *; do
    if [[ -f $file && $file == *Dice* ]]; then
      mv "$file" "${file//Dice/Ring}"
    fi
  done

  # Then handle subdirectories
  for subdir in *; do
    if [[ -d $subdir && $subdir == *Dice* ]]; then
      mv "$subdir" "${subdir//Dice/Ring}"
      subdir="${subdir//Dice/Ring}"
    fi
    if [[ -d $subdir ]]; then
      rename_files_and_directories "$subdir"
    fi
  done
  cd ..
}

# Call the recursive function starting from the current directory
rename_files_and_directories "$(pwd)"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)