- 1 year ago
Batch Replace Character in File Names
To batch replace a character in multiple file names using a Windows batch script, you can use the ren
command and a for
loop. Here's an example script that replaces a specific character (e.g., underscore "_") with another character (e.g., hyphen "-") in file names within a directory:
batch@echo off
setlocal enabledelayedexpansion
set "search=_"
set "replace=-"
for %%F in (*) do (
set "filename=%%~nF"
set "newname=!filename:%search%=%replace%!"
if not "!newname!"=="%%~nF" (
ren "%%F" "!newname!%%~xF"
)
)
endlocal
Here's how the script works:
The
set
commands define the search and replace strings. Adjust thesearch
andreplace
variables to match your specific requirements.The
for
loop iterates over each file (%%F
) in the current directory.Within the loop, the file name without extension is extracted using
%%~nF
and stored in thefilename
variable.The
set
command with delayed expansion (enabledelayedexpansion
) replaces thesearch
string with thereplace
string in thefilename
variable using string substitution (!filename:%search%=%replace%!
).If the new name is different from the original file name, the
ren
command is used to rename the file. The original file name (%%F
) is replaced with the new name (!newname!
) while preserving the original file extension (%%~xF
).The script completes, and all affected file names are replaced accordingly.
Save the script with a .bat
extension, place it in the directory containing the files you want to rename, and run it. The script will iterate through the files and replace the specified character in their names.