I am using below code to delete .txt
files not starting "S"
:
del [^S]*.txt
but its not working.
How this can be achieved?
I am using below code to delete .txt
files not starting "S"
:
del [^S]*.txt
but its not working.
How this can be achieved?
Why not just move S*.txt
to other folder, delete all, and then move back?
move S*.txt somefolder\
del *.txt
move somefolder\S*.txt .\
This isn't pretty but you can:
Here's an example:
for /f %F in ('dir S*.txt /B') do del %F /f
This does not address recursive searches or anything more advanced than the stated question.
UPDATE: I should have just said 'Use Powershell if you can'. Command prompt is a horrible shell:
gci -Filter S*.txt -recurse | rm
For a windows Vista or later os, try this
@echo off
setlocal enableextensions disabledelayedexpansion
set "targetFolder=%cd%"
set "tempFolder=%temp%\%~nx0.%random%.tmp"
md "%tempFolder%" >nul 2>nul
robocopy "%tempFolder%" "%targetFolder%" /nocopy /purge /xf s* /l
rd "%tempFolder%" >nul 2>nul
This creates an empty folder that is used as source for a purge of the target folder, that is, files that does not exist in source and exist in target are deleted. As the source is empty, all the files are deleted, but the /xf s*
indicates to robocopy
that files starting with a s
should be excluded. The ending /l
switch is included to only list the files that will be deleted. If the output is correct, remove it.
For versions of windows without robocopy
, this can be used.
@echo off
setlocal enableextensions disabledelayedexpansion
set "targetFolder=%cd%"
for /f "delims=" %%a in ('
dir /b /a-d "%targetFolder%" ^| findstr /i /v /b /c:"s"
') do echo del "%%~fa"
It is less efficient as a del
command will be executed for each of the files to be deleted. The idea is to retrieve the list of all files with a dir
command and use findstr
to, ignoring case (/i
) filter to only retrieve the list of elements that does not include (/v
) at the beginning of the line (/b
) the string S
(/c:"s"
)
del
commands are only echoed to console. If the output is correct, remove the echo
command