How to replace a single character in Windows filenames using a batch file?
I have a Windows Server 2003 server that has a whole bunch of filenames that need renaming. Basically, I just need all -
(hyphens) replaced with _
(underscores), no matter where they are in the filename. Assume that there are no duplicates.
I can do this on my Mac with a little script but the files are too large and crazy to transfer to my Mac, rename, then go back to the server. Is it possible to do this in a Windows command prompt without having to download a renamer or any additional software?
From the command prompt - assuming that all of your files are in the same directory:
ONE-LINER
for /f "tokens=* delims= " %i in ('dir /b "*.txt"') do Set LIST=%i& set LIST | ren "%~fi" "%LIST:-=_%"
Keep in mind that this is a one shot per command prompt window. That means if you cancel this for any reason, then you'll need to open another command prompt and run again.
Batch File to replace one character in a filename with another character
Consider using a free GUI app to hold your hand: http://www.bulkrenameutility.co.uk/Main_Intro.php
If you must this yourself with a batch file, be super careful! Batch scripts don't have an "undo" button. If you execute your bat script which applies to all files recursively under somewhere like C:
, you've just renamed every file on your computer and it will immediately stop working and fail to boot. You'll have to do an full OS reinstall. Always have a backup!
First you'll have to decide do you want the batch file to work on a single file? To work on all files in a directory? Or do have it done recursively (all files/folders under a directory). Here are some pointers:
Batch file to replace all underscores _
with the letter M
to all files in current directory
Put this in a batch file named change_underscores_in_this_directory.bat
@echo off
setlocal enabledelayedexpansion
for %%a in (*_*) do (
set file=%%a
ren "!file!" "!file:_=M!"
)
Execute it, and all the files in that directory with an underscore will be changed to an 'M'.
Use a Batch File to replace spaces with nothing (removing the spaces):
https://stackoverflow.com/questions/11270453/how-to-remove-spaces-from-file-names-in-bulk
Use a Batch File to replace spaces with underscores, Recursively:
https://stackoverflow.com/questions/1613644/how-to-replace-names-recursively-via-windows-batch-operation