united states of america usa  linkedinfacebook   Call Us Today: (786) 646-6461

Windows batch script to replace spaces with underscores

Command PromptWe regularly share some of the scripts that our IT technicians and support staff puts together (or finds online), especially if we think it may be useful to someone. Below is an example of a windows script (batch) that replaces file names with spaces to underscores. (For example: "file name.txt" will be changed to "file_name.txt")

The script recursively goes through the directories and makes adjustments.

For our particular IT task the script was used on .txt files (we we automatically manipulating files on a Linux box, coming from Windows, so they had to be free of spacing in files for successful copy), but it can be used on any: just replace *.txt with any other extension (or simply *.* for any files):

SET location=C:\TestDir
for /R %location% %%A in (*.txt) do call :repl "%%A"
goto :eof 

:repl
set "_fn=%~nx1"
ren %1 "%_fn: =_%"

We are an IT consulting company and provide support for Apple, Linux and Windows systems (both servers and workstations). If you or your firms requires IT support or consulting, feel free to contact us -- our IT specialists will be glad to assist.