Lets say I have a directory that looks something like this:
--FolderParent
--FolderChild1
--File1.abc
--File2.abcd
--FolderChild2
--File1.abc
--File2.abcd
I would like to delete File.abc without deleting File2.abcd. I have tried running these commands inside FolderParent
del /S *.abc
and
del /S *".abc"
but those both also delete File2.abcd.
CodePudding user response:
A bit of work is required to confirm the file doesn't have a long extension
use the *
wildcard in a dir /b
command, pipe it to findstr
with /R
regex with $
eol flag. capture the result of these steps using a for loop, and del
the result.
Double all %
characters for batch file.
For /f "delims=" %G in ('dir /b/s/a:-D "*.abc" ^| findstr /r "[\.][a][b][c]$"')Do del "%G" 2> nul
CodePudding user response:
Your problem is that the majority of the built-in commands and utilities, use the 8.3 names. You could disable the default setting of using them in Windows, (however), it will not remove any 'short' names already defined at that time.
The simplest way therefore, is to use a built-in utility which ignores 8.3 naming, where.exe
:
In cmd:
For /F "Delims=" %G In ('Set "PATHEXT=" ^& %SystemRoot%\System32\where.exe /R ".\FolderParent" "*.abc" 2^>NUL') Do @Del /A /F "%G"
Or in a batch-file:
@For /F "Delims=" %%G In ('Set "PATHEXT=" ^& %SystemRoot%\System32\where.exe /R ".\FolderParent" "*.abc" 2^>NUL') Do @Del /A /F "%%G"
CodePudding user response:
PowerShell does not have some of the anomalies of cmd.exe. When you are sure the correct files will be deleted, remove the -WhatIf
from the Remove-Item
command.
Get-ChildItem -Recurse -Path 'C:\ParentFolder' -Filter '*.abc' | Remove-Item -WhatIf
If you must run from cmd.exe:
powershell -Nologo -NoProfile -Command ^
"Get-ChildItem -Recurse -Path 'C:\ParentFolder' -Filter '*.abc' | Remove-Item -WhatIf
"