canada flag  linkedinfacebook   Call Us Today: (613) 494-5010

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.

 The current script was used on .txt files, 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 

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.

Original article posted on ALT Technical Miami.

Last updated Mar 3, 2019