How do I delete certain characters or replace certain characters with other characters by some batch file execution, for filenames of all files in a Windows folder in one go, is there a DOS command for that?
This question is related to
windows
file
powershell
batch-file
cmd
I would recommend the rename
command for this. Type ren /?
at the command line for more help.
A one-liner command in Windows PowerShell to delete or rename certain characters will be as below. (here the whitespace is being replaced with underscore)
Dir | Rename-Item –NewName { $_.name –replace " ","_" }
The PowerShell answers are good, but the Rename-Item command doesn't work in the same target directory unless ALL of your files have the unwanted character in them (fails if it finds duplicates).
If you're like me and had a mix of good names and bad names, try this script instead (will replace spaces with an underscore):
Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace(" ", "_") }
This batch file can help, but it has some limitations. The filename characters = and % cannot be replaced (going from memory here) and an ^ in the filenames might be a problem too.
In this portion %newname: =_%
on every line in the lower block it replaces the character after :
with the character after =
so as it stands the bunch of characters are going to be replaced with an underscore.
Remove the echo
to activate the ren command as it will merely print the commands to the console window until you do.
It will only process the current folder, unless you add /s
to the DIR command portion and then it will process all folders under the current one too.
To delete a certain character, remove the character from after the = sign. In %newname:z=%
an entry like this would remove all z characters (case insensitive).
@echo off
for /f "delims=" %%a in ('dir /a:-d /o:n /b') do call :next "%%a"
pause
GOTO:EOF
:next
set "newname=%~nx1"
set "newname=%newname: =_%"
set "newname=%newname:)=_%"
set "newname=%newname:(=_%"
set "newname=%newname:&=_%"
set "newname=%newname:^=_%"
set "newname=%newname:$=_%"
set "newname=%newname:#=_%"
set "newname=%newname:@=_%"
set "newname=%newname:!=_%"
set "newname=%newname:-=_%"
set "newname=%newname:+=_%"
set "newname=%newname:}=_%"
set "newname=%newname:{=_%"
set "newname=%newname:]=_%"
set "newname=%newname:[=_%"
set "newname=%newname:;=_%"
set "newname=%newname:'=_%"
set "newname=%newname:`=_%"
set "newname=%newname:,=_%"
echo ren %1 "%newname%
Source: Stackoverflow.com