Home » Questions » Computers [ Ask a new question ]

How to replace a single character in Windows filenames using a batch file?

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.

Asked by: Guest | Views: 184
Total answers/comments: 2
Guest [Entry]

"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."
Guest [Entry]

"Found it on stackoverflow:

stackoverflow.com/questions/261515/batch-file-script-to-remove-special-characters-from-filenames-windows

Set fso = CreateObject(""Scripting.FileSystemObject"")
Set re = New RegExp

re.Pattern = ""[-]"" ' put all characters that you want to strip inside the brackets'
re.IgnoreCase = True
re.Global = True

If WScript.Arguments.Unnamed.Count = 1 Then
If fso.FolderExists(WScript.Arguments.Unnamed(0)) Then
Recurse fso.GetFolder(WScript.Arguments.Unnamed(0))
Else
WScript.Echo ""Folder not found.""
End If
Else
WScript.Echo ""Please give folder name as argument 1.""
End If

Sub Recurse(f)
For Each sf In f.SubFolders
Recurse sf
WScript.Echo sf.Name, "" -> "", re.Replace(sf.Name, ""_"")
sf.Name = re.Replace(sf.Name, ""_"")
Next
For Each sf In f.Files
WScript.Echo sf.Name, "" -> "", re.Replace(sf.Name, ""_"")

If sf.Name <> re.Replace(sf.Name, ""_"" ) Then
sf.Name = re.Replace(sf.Name, ""_"")
End If
Next
End Sub"