Created
February 11, 2024 15:59
-
-
Save jorcelinojunior/bafe17f3f7a1372aa34e7bb03e34356a to your computer and use it in GitHub Desktop.
Script to recursively rename directories and files from 'foo' to 'bar', with a simulation mode available.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
SEARCH_DIR="./src" | |
SEARCH_FOR="foo" | |
REPLACE_WITH="bar" | |
SIMULATE=false | |
# Function to rename matching files and directories | |
rename_matches() { | |
local path="$1" | |
# Directories | |
find "$path" -depth ! -path "$path" -type d -name "*$SEARCH_FOR*" | while read -r dir ; do | |
local new_dir="${dir//$SEARCH_FOR/$REPLACE_WITH}" | |
echo "Renaming directory: $dir -> $new_dir" | |
if [ "$SIMULATE" = false ] ; then | |
mv "$dir" "$new_dir" | |
else | |
# Update path for simulation | |
path="$new_dir" | |
fi | |
done | |
# Files | |
find "$path" -type f -name "*$SEARCH_FOR*" | while read -r file ; do | |
local dir_path=$(dirname "$file") | |
local new_dir_path="${dir_path//$SEARCH_FOR/$REPLACE_WITH}" | |
local new_file="${file//$SEARCH_FOR/$REPLACE_WITH}" | |
echo "Renaming file: $file -> $new_file" | |
if [ "$SIMULATE" = false ] ; then | |
mv "$file" "$new_file" | |
fi | |
done | |
} | |
# Check if the script should simulate operations | |
if [ "$1" = "--simulate" ] || [ "$1" = "-s" ]; then | |
SIMULATE=true | |
echo "Simulation mode activated. No changes will be made to files." | |
fi | |
# Execute renaming (or simulation) | |
rename_matches "$SEARCH_DIR" | |
echo "Process completed." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Rename Script Explanation and Usage
This Bash script is designed to streamline the process of bulk renaming directories and files in a project. It targets items containing the term "exercise," replacing them with "sentence," while maintaining the integrity of subdirectory and file structures.
Key Features:
Setup and Execution:
rename_script.sh
.chmod +x rename_script.sh
to grant execution permissions.SEARCH_DIR
,SEARCH_FOR
, andREPLACE_WITH
variables within the script to suit your specific requirements../rename_script.sh
. To enable simulation mode and prevent any real changes, add the--simulate
or-s
flag when running the script.Example:
Executing the script without simulation flags (
--simulate
or-s
) will directly apply the renaming actions. To preview these changes without committing them, ensure you activate simulation mode. This feature is invaluable for ensuring your project's naming conventions remain consistent and accurate.Before initiating the script, creating a project backup is advisable to mitigate any risk of data loss.