Batch file script to remove special characters from filenames (Windows)

njr101 picture njr101 · Nov 4, 2008 · Viewed 83.5k times · Source

I have a large set of files, some of which contain special characters in the filename (e.g. ä,ö,%, and others). I'd like a script file to iterate over these files and rename them removing the special characters. I don't really mind what it does, but it could replace them with underscores for example e.g.

Störung%20.doc would be renamed to St_rung_20.doc

In order of preference:

  1. A Windiws batch file
  2. A Windows script file to run with cscript (vbs)
  3. A third party piece of software that can be run from the command-line (i.e. no user interaction required)
  4. Another language script file, for which I'd have to install an additional script engine

Background: I'm trying to encrypt these file with GnuPG on Windows but it doesn't seem to handle special characters in filenames with the --encrypt-files option.

Answer

Tomalak picture Tomalak · Nov 4, 2008

Have you tried setting cmd.exe into another codepage before you feed the file names to gnupg? Issue chcp 65001 to set cmd.exe to Unicode beforehand and try again.

If that fails, the following VBScript would do it:

Option Explicit

Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
Dim invalidChars: Set invalidChars = New RegExp

' put all characters that you want to strip inside the brackets
invalidChars.Pattern =  "[äöüß&%]"
invalidChars.IgnoreCase = True
invalidChars.Global = True

If WScript.Arguments.Unnamed.Count = 0 Then
  WScript.Echo "Please give folder name as argument 1."
  WScript.Quit 1
End If

Recurse fso.GetFolder(WScript.Arguments.Unnamed(0))

Sub Recurse(f)
  Dim item

  For Each item In f.SubFolders
    Recurse item
    Sanitize item
  Next
  For Each item In f.Files
    Sanitize item
  Next
End Sub

Sub Sanitize(folderOrFile)
  Dim newName: newName = invalidChars.Replace(folderOrFile.Name, "_")
  If folderOrFile.Name = newName Then Exit Sub
  WScript.Echo folderOrFile.Name, " -> ", newName
  folderOrFile.Name = newName 
End Sub

call it like this:

cscript replace.vbs "c:\path\to\my\files"

You can also drag&drop a folder onto it in Windows Explorer.