Batch rename files using the parent directory name

After coming across suitable images, I save them immediately. However, over time, the directories and files of images sourced from the internet became extremely cluttered. I started reclassifying and organizing them, moving images with similar attributes to appropriate directories. Ultimately, while the images were neatly categorized, their arbitrary filenames were irksome. Facing this issue, I consulted Google and eventually stumbled upon an excellent solution: Batch rename files using the parent directory name. Open the Terminal app, then enter the following bash script code and press Enter to run:
for dir in */; do
    count=1
    for file in "${dir}"*; do
        if [[ -f "$file" ]]; then
            base=$(basename "$file")
            ext="${base##*.}"
            newname="${dir%/}_${count}.${ext}"
            mv "$file" "${dir}${newname}"
            ((count++))
        fi
    done
done
This script will iterate through each subdirectory and rename the image files inside to the name of the parent directory followed by an incremental number while retaining the original file extension.
  1. Please use the cd command in the Terminal app to navigate to the top directory containing the images you want to rename.
  2. Enter the bash script and press the Enter key to execute the command.
[caption id="" align="aligncenter" width="526"] BATCH RENAME FILES USING THE PARENT DIRECTORY NAME[/caption] Note:
  1. Please make sure to backup your data as a precaution.
  2. The provided script is written based on your specific requirements. It assumes you are in the parent directory of these images and that each subdirectory contains the image files you wish to rename.
In fact, not only for image files, the aforementioned code can also rename other types of files accordingly. However, data is crucial. Please ensure you back up your data before proceeding. I can't stress this enough: back up your data, back up your data, back up your data! Other Mac Tips and Tricks: REPEATED “TRUST” ALERTS ON IPHONE-MACBOOK CONNECTION – DISABLE USBD SERVICE Batch Script – Commands Batch Command Post Lists
Batch command to Generate Text Files Based on Lines from a Source File

Batch command to extract the filenames in the current directory

Batch command to create blank text files

Batch rename files using the parent directory name

Comments

Popular posts from this blog

Installing Python3.10.x Version on Mac and Set the Environment

Adding Specific Applications to Windows 11 Startup Apps

HTTPS(SSL) Blocks WordPress Admin Access