Comprehensive BAT Script for Batch Renaming Image Files
Automate your file organization with precision and efficiency
Key Takeaways
- Dynamic Renaming Logic: Adjusts based on folder depth to ensure accurate file naming.
- UTF-8 Support: Handles non-ASCII characters seamlessly for diverse file names.
- User Confirmation and Backup: Provides a preview before execution and secures original files.
Introduction
Organizing large collections of image files can be a daunting task, especially when dealing with complex folder structures. This BAT script is designed to automate the renaming process of .jpg and .png files based on their folder hierarchy. It ensures that filenames are consistent with their respective folder names, whether they are located one or two levels deep within the main directory. Additionally, the script supports UTF-8 encoding to handle non-ASCII characters, creates backups before renaming, and provides a user-friendly confirmation step before executing the changes.
Script Overview
The script performs the following operations:
- Prompts the user to enter the path of the folder to be processed.
- Recursively traverses all subfolders and searches for
.jpgand.pngfiles. - Determines the depth of each image file relative to the main folder.
- Generates new filenames based on the folder hierarchy:
- If the file is one level deep:
[Subfolder1]_[Original Number]_p0.jpg - If the file is two levels deep:
[Subfolder1][Subfolder2]_[Original Number]_p0.jpg
- If the file is one level deep:
- Displays a list of planned changes and prompts the user for confirmation.
- Upon confirmation, creates backups of the original files and performs the renaming.
Complete BAT Script
Save the following script with a .bat extension (e.g., rename_images.bat) and execute it by double-clicking:
@echo off
REM Enable UTF-8 encoding and delayed variable expansion
chcp 65001 > nul
setlocal EnableDelayedExpansion
:: Step 1: Prompt user for folder path
echo.
echo Enter the path of the folder to be processed (no quotation marks needed):
set /p "folderPath=Folder Path: "
:: Remove any trailing backslash
if "%folderPath:~-1%"=="\" set "folderPath=%folderPath:~0,-1%"
:: Validate the folder path
if not exist "%folderPath%" (
echo The folder "%folderPath%" does not exist. Please check the path and try again.
pause
exit /b
)
:: Step 2: Traverse subfolders and find JPG/PNG files
echo.
echo Searching for JPG and PNG files in "%folderPath%" and its subdirectories...
set "fileList="
for /r "%folderPath%" %%F in (*.jpg *.png) do (
set "fileList=!fileList!%%F|"
)
:: Check if any files are found
if "!fileList!"=="" (
echo No JPG or PNG files found in the specified directory.
pause
exit /b
)
:: Step 3: Determine renaming logic and prepare rename list
echo.
echo Preparing the list of files to be renamed...
set "renameList="
for %%F in ("!fileList!") do (
set "fullPath=%%F"
set "fileName=%%~nF"
set "fileExt=%%~xF"
set "fileDir=%%~dpF"
:: Remove the base folder path from the file directory
set "relativePath=!fileDir:%folderPath%\=!"
:: Count the number of subfolders to determine depth
set "depth=0"
for %%A in ("!relativePath:~0,-1!") do (
for %%B in (%%~A) do (
set /a depth+=1
)
)
:: Extract subfolder names based on depth
if !depth! EQU 1 (
set "subFolder1=%%~nA"
set "newName=!subFolder1!_!fileName!!fileExt!"
) else if !depth! GEQ 2 (
for /f "tokens=1,2 delims=\" %%a in ("!relativePath!") do (
set "subFolder1=%%a"
set "subFolder2=%%b"
)
set "newName=!subFolder1!!subFolder2!_!fileName!!fileExt!"
) else (
set "newName=!fileName!!fileExt!"
)
:: Add to rename list
set "renameList=!renameList!!fullPath!|!fileDir!!newName!|"
)
:: Step 4: Display planned changes and confirm
echo.
echo The following changes will be made:
echo ------------------------------------
echo Original File Path ^| New File Path
echo ------------------------------------
for %%G in ("!renameList!") do (
for /f "tokens=1,2 delims=|" %%a in ("%%~G") do (
echo %%a ^| %%b
)
)
echo ------------------------------------
echo.
set /p "confirm=Do you want to proceed with renaming and backing up the files? (Y/N): "
if /i not "!confirm!"=="Y" (
echo Operation cancelled by the user.
pause
exit /b
)
:: Step 5: Perform renaming and create backups
echo.
echo Creating backups and renaming files...
set "backupDir=%folderPath%\Backup_%date:~0,4%%date:~5,2%%date:~8,2%_%time:~0,2%%time:~3,2%%time:~6,2%"
set "backupDir=%backupDir: =0%"
mkdir "!backupDir!" > nul
for %%G in ("!renameList!") do (
for /f "tokens=1,2 delims=|" %%a in ("%%~G") do (
:: Create backup
copy "%%a" "!backupDir!\" > nul
:: Rename the file
ren "%%a" "%%~nb%%~xb" > nul
echo Renamed: "%%a" -> "%%~b"
)
)
echo.
echo All files have been renamed successfully.
echo Backups are stored in: "!backupDir!"
pause
endlocal
Script Breakdown
1. UTF-8 Support and Environment Setup
The script begins by setting the code page to UTF-8 using chcp 65001, ensuring it can handle filenames with non-ASCII characters. Delayed variable expansion is enabled to allow for dynamic variable updates within loops.
2. User Input and Validation
The user is prompted to enter the path of the folder to be processed. The script then verifies whether the entered path exists. If not, it notifies the user and terminates the operation.
3. File Traversal and Listing
The script uses a for /r loop to recursively traverse all subdirectories within the specified folder, searching for files with .jpg and .png extensions. These files are compiled into a list for further processing.
4. Renaming Logic Determination
For each found image file, the script determines its relative path to assess the depth within the folder structure:
-
Single-Level Depth: If a file is one level deep, the new filename is constructed by prefixing the immediate subfolder name to the original filename (e.g.,
ALC10307_0_p0.jpg). -
Two-Level Depth: If a file is two levels deep, both the first and second subfolder names are concatenated and prefixed to the original filename (e.g.,
ALC10134藏蓝_0_p0.jpg).
Files that do not meet these depth criteria retain their original filenames.
5. User Confirmation
Before making any changes, the script presents a summary of all planned renaming actions. The user is then prompted to confirm whether to proceed with the renaming and backup operations.
6. Backup Creation and Renaming Execution
Upon user confirmation, the script creates a backup directory named with the current date and time to store copies of the original files. It then proceeds to rename each file as per the determined new filenames, ensuring that all original files are safely backed up before any modifications.
Example Scenarios
Consider the following examples to understand how the script operates:
Scenario 1: Single-Level Depth
Before Renaming:
D:\电商\试验场\ALC 1.13 成图\ALC10307\0_p0.jpg
After Renaming:
D:\电商\试验场\ALC 1.13 成图\ALC10307\ALC10307_0_p0.jpg
Scenario 2: Two-Level Depth
Before Renaming:
D:\电商\试验场\ALC 1.13 成图\ALC10134\藏蓝\0_p0.jpg
After Renaming:
D:\电商\试验场\ALC 1.13 成图\ALC10134\藏蓝\ALC10134藏蓝_0_p0.jpg
Error Handling and Edge Cases
- Invalid Folder Path: The script verifies the existence of the provided folder path. If invalid, it alerts the user and exits gracefully.
- No Image Files Found: If no
.jpgor.pngfiles are detected, the script informs the user and terminates. - File Naming Conflicts: Existing files with the new names will be overwritten. Users are advised to ensure that backup operations are successful to prevent data loss.
Conclusion
This BAT script provides a robust solution for organizing and renaming image files based on their directory structure. By automating the renaming process, it saves time and reduces the likelihood of manual errors. The inclusion of UTF-8 support ensures compatibility with a wide range of characters, making it versatile for various user needs. Additionally, the script's backup feature guarantees that original files are preserved, offering peace of mind during the renaming process.
References
The script and its features are synthesized from standard BAT scripting practices and tailored to meet the specific requirements outlined by the user.
Last updated January 19, 2025