The Windows Command Processor cmd.exe
has two internal commands for deletion of files and folders:
- The command DEL is for the deletion of files with usage help output on running in a Windows command prompt window either
help del
ordel /?
. - The command RMDIR or with shorter name RD is for removal of directories with usage help output on running in a Windows command prompt window either
help rmdir
orrmdir /?
orhelp rd
orrd /?
.
Deletion of all *.svn files in an entire folder tree
There can be used in a Windows command prompt window or a Windows batch file the following command to delete really all files of which long or short 8.3 file name is matched by the wildcard pattern *.svn
in the directory %USERPROFILE%\Projects
or any of its subdirectories:
del /A /F /Q /S "%USERPROFILE%\Projects\*.svn" >nul 2>&1
The usage of option /A
to match all files independent on the file attributes replaces the implicit default /A-H
to ignore hidden files. So even files with hidden attribute are deleted by this command because of using the option /A
. Files matched by wildcard pattern *.svn
with hidden attribute set are ignored on not using the option /A
.
The option /F
forces a deletion of files with file extension .svn
which have the read-only attribute set. There would be output the error message Access is denied.
if a *.svn
file has the read-only attribute set and the option /F
is not used on running the command DEL.
The quiet option /Q
prevents the user confirmation prompt Are you sure (Y/N)?
.
The option /S
results in searching not only in the specified directory, but also in all its subdirectories including those with hidden attribute set even on not using option /A
for files of which long or short 8.3 name is matched by the wildcard pattern *.svn
.
The two redirections >nul
and 2>&1
result in redirecting the list of deleted files output to handle STDOUT (standard output) and the error messages output to handle STDERR (standard error) to the device NUL to suppress every output.
There are deleted also hard links and symbolic links matched by the wildcard pattern *.svn
on using this command, but not the files linked to on having a file name not ending with .svn
or being in a different directory tree.
Files matched by the wildcard pattern *.svn
currently opened by a process (program/application) with using shared access permissions to deny all other processes to delete the file as long as being opened by this process are not deleted by this command. File system permissions can result also in files not being deleted by this command.
Deletion of all *.svn folders in an entire folder tree
There can be used in a Windows command prompt window the following command to remove really all folders matching in long or short 8.3 folder name the wildcard pattern *.svn
in the directory %USERPROFILE%\Projects
and all its subdirectories:
for /F "delims=" %I in ('dir "%USERPROFILE%\Projects\*.svn" /AD /B /S 2^>nul') do @rd /Q /S "%I" 2>nul
The same command line for usage in a batch file containing @echo off
at top is:
for /F "delims=" %%I in ('dir "%USERPROFILE%\Projects\*.svn" /AD /B /S 2^>nul') do rd /Q /S "%%I" 2>nul
There is executed on more cmd.exe
in background with option /c
and the command line specified between '
as additional arguments to run in background the Windows Command Processor internal command DIR to search
- in the specified directory
%USERPROFILE%\Projects
- and in all its subdirectories because of option
/S
- for just directories because of using the option
/AD
which includes also junctions and symbolic directory links - matching the wildcard pattern
*.svn
.
The file system entries (= directory names) matched by these criteria are output in bare format because of option /B
with full path because of option /S
to handle STDOUT of the background command process without surrounding "
even on full directory name containing a space or one of these characters &()[]{}^=;!'+,`~
. The error message output by DIR on not finding any name matching these criteria is redirected to device NUL to suppress it.
The redirection operator >
must be escaped with caret character ^
on FOR command line to be interpreted as literal character when the Windows Command Processor parses this command line before executing the command FOR which executes the embedded dir
command line with using a separate command process started in background.
The output list of directory names with their full paths to handle STDOUT is captured by cmd.exe
processing the batch file and processed by FOR after started cmd.exe
closed itself.
The FOR /F option delims=
defines an empty list of string delimiters which results in each entire directory name is assigned completely one after the other to the specified loop variable I
.
The command RD is executed to delete quietly because of option /Q
the directory with all files and all subdirectories because of option /S
.
There are deleted also junctions (soft links) and symbolic directory links matched by the wildcard pattern *.svn
on using this command, but not the directories linked to on having a directory name not ending with .svn
or being in a different directory tree.
A directory matched by the wildcard pattern *.svn
in which a file is currently opened by a process (program/application) with using shared access permissions to deny all other processes to delete the file as long as being opened by this process is not deleted by this command and of course also no directory above the directory containing the file which cannot be deleted at the moment. File system permissions can result also in directories not being deleted by this command. Windows prevents by default also the deletion of a directory which is the current working directory of any running process.
Other useful information regarding to deletion of files and folders
The directory path %USERPROFILE%\Projects\
can be removed completely or replaced by .\
in the commands above to delete the files and folders matching the wildcard pattern *.svn
in the current directory of the Windows Command Processor process which executes the commands.
The directory path %USERPROFILE%\Projects\
can be replaced by %~dp0
to delete the files and folders matching the wildcard pattern *.svn
in the directory of the batch file on using the command lines above in a batch file independent on which directory is the current directory on execution of the batch file.
The directory path %USERPROFILE%\Projects\
can be replaced also by a relative path. Please read the Microsoft documentation about Naming Files, Paths, and Namespaces for more details about relative paths.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
del /?
dir /?
for /?
rd /?
Run mklink /?
for help on how to create file and directory links explained very well by MKLink.
See also:
- Microsoft documentation for the Windows commands
- SS64.com — A-Z index of Windows CMD commands
The Windows Command Processor cmd.exe
has two internal commands for deletion of files and folders:
- The command DEL is for the deletion of files with usage help output on running in a Windows command prompt window either
help del
ordel /?
. - The command RMDIR or with shorter name RD is for removal of directories with usage help output on running in a Windows command prompt window either
help rmdir
orrmdir /?
orhelp rd
orrd /?
.
Deletion of all *.svn files in an entire folder tree
There can be used in a Windows command prompt window or a Windows batch file the following command to delete really all files of which long or short 8.3 file name is matched by the wildcard pattern *.svn
in the directory %USERPROFILE%\Projects
or any of its subdirectories:
del /A /F /Q /S "%USERPROFILE%\Projects\*.svn" >nul 2>&1
The usage of option /A
to match all files independent on the file attributes replaces the implicit default /A-H
to ignore hidden files. So even files with hidden attribute are deleted by this command because of using the option /A
. Files matched by wildcard pattern *.svn
with hidden attribute set are ignored on not using the option /A
.
The option /F
forces a deletion of files with file extension .svn
which have the read-only attribute set. There would be output the error message Access is denied.
if a *.svn
file has the read-only attribute set and the option /F
is not used on running the command DEL.
The quiet option /Q
prevents the user confirmation prompt Are you sure (Y/N)?
.
The option /S
results in searching not only in the specified directory, but also in all its subdirectories including those with hidden attribute set even on not using option /A
for files of which long or short 8.3 name is matched by the wildcard pattern *.svn
.
The two redirections >nul
and 2>&1
result in redirecting the list of deleted files output to handle STDOUT (standard output) and the error messages output to handle STDERR (standard error) to the device NUL to suppress every output.
There are deleted also hard links and symbolic links matched by the wildcard pattern *.svn
on using this command, but not the files linked to on having a file name not ending with .svn
or being in a different directory tree.
Files matched by the wildcard pattern *.svn
currently opened by a process (program/application) with using shared access permissions to deny all other processes to delete the file as long as being opened by this process are not deleted by this command. File system permissions can result also in files not being deleted by this command.
Deletion of all *.svn folders in an entire folder tree
There can be used in a Windows command prompt window the following command to remove really all folders matching in long or short 8.3 folder name the wildcard pattern *.svn
in the directory %USERPROFILE%\Projects
and all its subdirectories:
for /F "delims=" %I in ('dir "%USERPROFILE%\Projects\*.svn" /AD /B /S 2^>nul') do @rd /Q /S "%I" 2>nul
The same command line for usage in a batch file containing @echo off
at top is:
for /F "delims=" %%I in ('dir "%USERPROFILE%\Projects\*.svn" /AD /B /S 2^>nul') do rd /Q /S "%%I" 2>nul
There is executed on more cmd.exe
in background with option /c
and the command line specified between '
as additional arguments to run in background the Windows Command Processor internal command DIR to search
- in the specified directory
%USERPROFILE%\Projects
- and in all its subdirectories because of option
/S
- for just directories because of using the option
/AD
which includes also junctions and symbolic directory links - matching the wildcard pattern
*.svn
.
The file system entries (= directory names) matched by these criteria are output in bare format because of option /B
with full path because of option /S
to handle STDOUT of the background command process without surrounding "
even on full directory name containing a space or one of these characters &()[]{}^=;!'+,`~
. The error message output by DIR on not finding any name matching these criteria is redirected to device NUL to suppress it.
The redirection operator >
must be escaped with caret character ^
on FOR command line to be interpreted as literal character when the Windows Command Processor parses this command line before executing the command FOR which executes the embedded dir
command line with using a separate command process started in background.
The output list of directory names with their full paths to handle STDOUT is captured by cmd.exe
processing the batch file and processed by FOR after started cmd.exe
closed itself.
The FOR /F option delims=
defines an empty list of string delimiters which results in each entire directory name is assigned completely one after the other to the specified loop variable I
.
The command RD is executed to delete quietly because of option /Q
the directory with all files and all subdirectories because of option /S
.
There are deleted also junctions (soft links) and symbolic directory links matched by the wildcard pattern *.svn
on using this command, but not the directories linked to on having a directory name not ending with .svn
or being in a different directory tree.
A directory matched by the wildcard pattern *.svn
in which a file is currently opened by a process (program/application) with using shared access permissions to deny all other processes to delete the file as long as being opened by this process is not deleted by this command and of course also no directory above the directory containing the file which cannot be deleted at the moment. File system permissions can result also in directories not being deleted by this command. Windows prevents by default also the deletion of a directory which is the current working directory of any running process.
Other useful information regarding to deletion of files and folders
The directory path %USERPROFILE%\Projects\
can be removed completely or replaced by .\
in the commands above to delete the files and folders matching the wildcard pattern *.svn
in the current directory of the Windows Command Processor process which executes the commands.
The directory path %USERPROFILE%\Projects\
can be replaced by %~dp0
to delete the files and folders matching the wildcard pattern *.svn
in the directory of the batch file on using the command lines above in a batch file independent on which directory is the current directory on execution of the batch file.
The directory path %USERPROFILE%\Projects\
can be replaced also by a relative path. Please read the Microsoft documentation about Naming Files, Paths, and Namespaces for more details about relative paths.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
del /?
dir /?
for /?
rd /?
Run mklink /?
for help on how to create file and directory links explained very well by MKLink.
See also:
- Microsoft documentation for the Windows commands
- SS64.com — A-Z index of Windows CMD commands
Создавать папки нетрудно, однако, если у вас имеется сложная структура каталогов, из которой нужно удалить все файлы, вряд ли вы захотите создавать ее заново, удалив ее перед этим вместе с файлами. Впрочем, удалить все файлы, сохранив при этом структуру директорий очень даже просто, причем сделать это можно как минимум тремя путями. Первый способ предполагает копирование имеющейся структуры с игнорированием ее содержимого.
Копирование структуры
Воспользуемся для этих целей встроенной консольной утилитой XCOPY. Предположим, что у нас есть папка Data с вложенными каталогами, в которых содержаться некие файлы, которые нужно удалить.
Создав пустую папку Data в другом месте, открываем PowerShell или командную строку и выполняем команду XCOPY «путь-к-папке-с-файлами «путь-к-пустой-папке» /T /E.
В результате в пустой каталог Data будет скопировано дерево папок первой папки Data, но уже без файлов. Естественно, первую папку можно удалить.
С помощью Total Commander
Если у вас есть файловый менеджер Total Commander, используем встроенную функцию вывода содержимого без каталогов.
Зайдите в программе в каталог с содержимым и нажмите Ctrl + B.
В результате все содержащиеся в нём файлы, в том числе те, которые находятся во вложенных каталогах, будут выведены в панели файлового менеджера. Готово, теперь вам останется их только выделить и удалить.
Папки при этом останутся на месте.
Рекурсивным методом в PowerShell
Почистить папки от файлов можно и с помощью PowerShell.
Для этого в запущенной консоли выполняем команду:
Get-ChildItem -Path «путь-к-папке» -Include *.* -File -Recurse | foreach { $_.Delete()}
Этой командой мы рекурсивно проходим по каталогам, получаем список файлов и удаляем их. Удалены, однако, будут только те файлы, которые имеют расширение или точку в имени.
Приведенная здесь команда тем хороша, что позволяет удалять файлы по маске. Так, добавив к точке расширение TXT (*.txt*), вы удалите только текстовые файлы с данным расширением. Но есть у нее и свой недостаток, — все файлы удаляются мимо Корзины, поэтому перед очисткой каталогов всё же рекомендуется создавать их резервные копии.
Загрузка…
For the file example, I would like to delete all files matching .+?[a-f0-9]{4}.html (i.e. any html file ending in a four digit hexadecimal). So paged47c.html would be deleted, but page.html would remain.
For the folder example, I would like to delete all folders matching .+?[A-Z]+ (i.e. any folder containing a capital letter). So some-folderSE93_89ds/ would be deleted, but some-folder/ would remain.
I don’t work much with the command line, but I could probably get an example involving «del» to work for me. Alternatively, is there a simple GUI program for Windows that would do this?
asked Apr 6, 2012 at 21:15
I would say the easiest way, albeit not the direct route, is to do your specialized dir
command (you can use /b and /s switched to make it just list the filename and to recurse directories) and redirect it to a file. Open it in notepad (or insert your favorite editor), search and replace to add «del » to the beginning of the lines, save it off as mydel.bat, and execute.
So an example would be:
dir /s /b *.html > mydel.bat
notepad mydel.bat
call mydel.bat
answered Apr 6, 2012 at 22:04
pottsdlpottsdl
6414 silver badges10 bronze badges
1
Use the following line in powershell:
Get-ChildItem -Recurse C:\| where { ! $_.PSIsContainer } | Where-Object {$_.Name -match ".+?[a-f0-9]{4}.html"}
Is for the file case, for the folder case use:
Get-ChildItem -Recurse C:\| Where-Object { $_.PSIsContainer }| Where-Object {$_.Name -match ".+?[A-Z]+"}
Store those both in variables, and then use Remove-Item
Warning: In my command, I am using the root C:\
as the source location. If you do want to pipe it’s output to Remove-Item
and you are running this as administrator, its a bad idea. At the very least do one of the following:
- Specifically exclude
Windows
- Using the
what-if
flag - Don’t run as administrator (if the files that you are matching are not in a protected directory, it won’t matter)
- Don’t run use
C:\
but rather from some safer place
answered Apr 6, 2012 at 22:05
soandossoandos
24.2k28 gold badges102 silver badges134 bronze badges
2
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.
i have a folder with 2K+ files in it, i need to delete around 200, i have a txt file with all the file names i need removed ordered in a list, how do i remove the specific files from the folder using the list? (OS is windows 7)
Hennes
64.8k7 gold badges111 silver badges168 bronze badges
asked Nov 9, 2011 at 17:19
Simple way is copy the txt file to a file called mydel.bat
in the directory of the files to delete. Using an editor like Microsoft Word edit this file. Do a global replace on Newline normally ^p
in Word. Replace it with space/f^pdelspace
. This will change
File1.bin
File20.bin
File21.bin
to (with /f
for «force delete read-only files»):
File1.bin /f
del File20.bin /f
del File21.bin /f
del
Edit the fist line to add the del
space
and delete the last line.
Run the batch command.
Arjan
31k14 gold badges75 silver badges112 bronze badges
answered Nov 9, 2011 at 17:29
kingchriskingchris
6207 silver badges13 bronze badges
4
Type this on the command line, substituting your file for files_to_delete.txt
:
for /f %i in (files_to_delete.txt) do del %i
A version of this suitable to include in .cmd
files (double %%) and able to deal with spaces in file names:
for /f "delims=" %%f in (files_to_delete.txt) do del "%%f"
answered Nov 9, 2011 at 17:36
William JacksonWilliam Jackson
8,3741 gold badge37 silver badges45 bronze badges
6
Using PowerShell:
Get-Content c:\path\to\list.txt | Remove-Item
answered Nov 9, 2011 at 19:54
Siim KSiim K
7,8426 gold badges51 silver badges70 bronze badges
4
First method works after some changes:
- open Notepad
-
copy all file names with extension which need to be deleted after adding
del
at the beginning likedel File1.bin del File20.bin del File21.bin
-
save the file as
xyz.bat
in the same folder - run the file
Arjan
31k14 gold badges75 silver badges112 bronze badges
answered May 21, 2015 at 6:39
1
I imagine it can be done with powershell.
Knowing Perl, I tend to use it for this sort of thing
perl -l -n -e "unlink" filenames.txt
answered Nov 9, 2011 at 17:34
RedGrittyBrickRedGrittyBrick
82.1k20 gold badges136 silver badges205 bronze badges
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.