Script to remove special characters from file names

I have a folder containing a large number of files. Many file names have "%" and / or "&"; characters in them.

eg Test&doc.pdf eg Test%doc.doc 

Is it possible to quickly remove the "%" and "&" characters using a Windows batch file, vbscript, or something similar?

All help would be greatly appreciated.

Thanks.

+4
batch-file
source share
3 answers

I quickly threw it together and did not test, but this VBScript should do the trick. Tell me if you need fancy stuff like recursive folder replacement etc.

 Set objFSO = CreateObject("Scripting.FileSystemObject") 'Your folder here objStartFolder = "X:\MYFOLDER" Set objFolder = objFSO.GetFolder(objStartFolder) Set regEx = New RegExp 'Your pattern here regEx.Pattern = "[&%]" Set colFiles = objFolder.Files For Each objFile in colFiles objFile.Rename(regEx.Replace(objFile.Name, "") Next 
+2
source share

Here you can do it in batch mode (if you're interested). The big limitation is that if you have file names with a symbol of more than one percent, this will not work, because the shell expands it to a variable. I do not know how to fix this.

It is launched from any directory in which the script is located, and works recursively on all subdirectories.

 @echo off setlocal enabledelayedexpansion for /f "usebackq delims=" %%N in (`dir /s /b`) do ( set var=%%~nN set var=!var:^&= ! set var=!var:%%= ! if not "!var!"=="%%~nN" ( if not exist "%%~dpN!var!%%~xN" ( echo "%%N" --^> "!var!%%~xN" ren "%%N" "!var!%%~xN" ) else ( echo File "!var!%%~xN" ^(from %%N^) already exists. ) ) ) 

For example, prints the output as follows:

 C:\batch\schar>schar "C:\batch\schar\Test%doc.doc" --> "Test doc.doc" "C:\batch\schar\Test%doc.pdf" --> "Test doc.pdf" File "Test doc.pdf" (from C:\batch\schar\Test&doc.pdf) already exists. "C:\batch\schar\subdir\FILE%here" --> "FILE here" 
+3
source share

@indiv

If someone can create a batch solution without character restrictions, I will be impressed by the mass.

Ok, I'll try.

 @echo off setlocal DisableDelayedExpansion for /f "usebackq delims=" %%N in (`dir /s /b`) do ( set var=%%~nxN setlocal EnableDelayedExpansion set "org=!var!" set "var=!var:&= !" set "var=!var:%%= !" if not "!var!"=="!org!" ( if not exist "%%~dpN!var!" ( echo "!org!" --^> "!var!" ren "!org!" "!var!" ) else ( echo File "!var!" ^(from !org!^) already exists. ) ) endlocal ) 

The trick is to toggle the slow expansion, because the for-loop-vars (%% N) extension should run without delaying the extension, otherwise you will lose exclamation points and get problems with caret. But you must use a delayed extension to process and modify strings.

But why? The answer lies in understanding the phases of the parser analyzer.

I tried to explain it here. how-does-the-windows-command-interpreter-cmd-exe-parse-scripts

+3
source share

All Articles