[英]Delete .txt file not start with any character in command prompt
I am using below code to delete .txt
files not starting "S"
: 我正在使用下面的代码删除不以
"S"
开头的.txt
文件:
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? 为什么不将
S*.txt
移至其他文件夹,将其全部删除,然后移回?
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 /B ^| find /v "S"') do del %F /f
UPDATE: In response to the down vote, here is a corrected and simplified 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'. 更新:我应该说“如果可以,请使用Powershell”。 Command prompt is a horrible shell:
命令提示符是一个可怕的shell:
gci -Filter S*.txt -recurse | rm
For a windows Vista or later os, try this 对于Windows Vista或更高版本的操作系统,请尝试此操作
@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. 由于源是空的,所有的文件被删除,但
/xf s*
指示robocopy
该开始用文件s
应排除在外。 The ending /l
switch is included to only list the files that will be deleted. 包含结尾的
/l
开关仅列出将要删除的文件。 If the output is correct, remove it. 如果输出正确,请将其删除。
For versions of windows without robocopy
, this can be used. 对于没有
robocopy
的Windows版本,可以使用。
@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. 由于要对要删除的每个文件执行
del
命令,因此效率较低。 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"
) 这个想法是使用
dir
命令检索所有文件的列表,并使用findstr
来忽略大小写( /i
)过滤器,仅检索在行首( /b
)不包括( /v
)的元素列表。 )字符串S
( /c:"s"
)
del
commands are only echoed to console. del
命令仅回显到控制台。 If the output is correct, remove the echo
command 如果输出正确,请删除
echo
命令
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.