Dos - Rename filenames without special characters

By xngo on July 10, 2019

REM *******************************************************************************
REM Description: Rename filenames(*.pdf and *.xls) without 
REM               specials characters(e.g. spaces, double underscores).
REM Note: Command Prompt's code page is different than Windows' code page. 
REM       Therefore, I switched Command Prompt's code page to be the same 
REM       as Windows' so that I can replace accent characters(e.g. à, é, â, etc ).
REM *******************************************************************************

REM Get all *.pdf and *.xls filenames.
FOR /F "delims=" %%W IN ('dir /b *.pdf *.xls') DO (
CALL :removeChars "%%W"
)
GOTO :EOF
 
 
:removeChars
  REM Get the current code page of the Command Prompt.
  For /F "Tokens=2 Delims=:" %%I In ('Chcp ') Do Set /A _CurCP=%%I
  REM Change code page to 1252
  Chcp 1252
 
  SET filename=%1
  
  REM Remove spaces
  SET filename=%filename: =.%
  REM Remove double underscores.
  SET filename=%filename:__=_%
  SET filename=%filename:._=_%
  SET filename=%filename:à=a%
  SET filename=%filename:â=a%
  SET filename=%filename:é=e%
  SET filename=%filename:è=e%

  REM Rename the filename without the specials characters.
  rename %1 %filename%
  
  REM Change back to the original code page of Command Prompt.
  Chcp %_CurCP%
  GOTO :EOF

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.