- Delete files from command line
- How to delete a file
- Delete files in bulk
- Delete multiple files
- Delete Read only files
- Как удалить файл или папку через командную строку Windows
- Удаление файлов через командную строку
- Удаление папок через командную строку
- cmd Delete Folder – How to Remove Files and Folders in Windows
- Kris Koishigawa
- How to open Command Prompt
- How to delete files with the del command
- How to force delete files with the del command
- How to delete folders with the rmdir command
- How to use the /s flag with rmdir
- Kris Koishigawa
Delete files from command line
Deleting files is one of the frequently done operation from Windows command prompt. This post explains how to use ‘del’ command from CMD for different use cases like deleting a single file, deleting files in bulk using wild cards etc. Before we start to look at the syntax, note that the command works only for files and can’t handle folders.
How to delete a file
Run del command with the name of the file to be deleted, you are done!
You do not see message after running the command if the file is deleted successfully. Error message is shown only when something goes wrong.
Delete files in bulk
Del command recognizes wildcard(*) and so can be used to delete files in bulk from CMD. Some examples below.
To delete all the files in current folder
To delete all the files with ‘log’ extension
Delete all files having the prefix ‘abc’
Delete all files having ‘PIC’ somewhere in the file name.
The above are the basic use cases of del command. Continue to read below for non trivial use cases.
Delete multiple files
‘Del’ command can accept multiple files as argument
Delete Read only files
We can’t delete a read-only file using simple‘del’ command. We get access denied error in this scenario.
A read-only file can be deleted by adding /F flag.
Alternatively, we can use the below command too
Is there any batch command to delete all zero byte sized files from cmd.
There is a way to remove folders from the commandline, use “RD” (remove directory), and it has a couple of silent switches, “RD /S /Q C:/Directory” will remove C:/Directory silently, I use this all the time. I think that the directory path has to be in quotations if it contains any spaces.
UAC might want to fight over deleting files, in that case, the command “takeown” to give you ownership of the file first, should get around that.
Sometimes we get an error when we try to delete a File or a folder for no reason , but of course there is a reason.We have many damage file or blocked files.Do not worry if we want to remove the error files or too long path files from our system,here I suggest a smooth way.So use “Long path tool” software and keep yourself.
Well done, I used this when del *1*.*
Will keep this in my reference book. Thanks a lot!
Is there a way to exclude filenames matching a pattern from a delete? For example, I want to delete all files except those whose names are like *xyz*
I am trying to delete csv files in DOS that have a date suffix of earlier
than 2 months ago. I need to do this dynamically, from a batch file.
Is this possible ? Many thanks.
Bethany
I want to delete a file from all the user’s profiles using cmd.
The file is on the desktop.
Name of the file-Hello My Name
I’m writing del %PUBLIC%\Desktop\Hello*My*Name.pdf,but that doesnt seem to work.
I also tried del %PUBLIC%\Desktop\*Hello* but that didnt work too.
Any help is appreciated
c. Using the for loop create 5 text files which start from letter a (ex: a1, a2, a3, a4, a5).
can you help me
create 5 files like this command.
for /l %a in (1 1 5) do mkdir File%a.
Как удалить файл или папку через командную строку Windows
Командная строка – мощный инструмент для автоматизации и упрощения многих задач, которые возникают при администрировании компьютера с операционной системой Windows. В этой статье мы рассмотрим команды DEL, ERASE, RD и RMDIR. С их помощью вы сможете удалять файлы и папки прямо из командной строки.
Удаление файлов через командную строку
Если вам нужно удалить файл через командную строку, то для этого нужно использовать команду DEL или ERASE . Эти команды являются синонимами и работают одинаково. Вы можете получить подробную информацию об этих командах, если введете их в командную строку с параметром « /? ». Например, вы можете ввести « del /? » и в консоль выведется вся основная информация о команде del .
Команда DEL (или ERASE ) предназначена для удаления одного или нескольких файлов и может принимать следующие параметры:
- /P – удаление с запросом подтверждения для каждого файла;
- /F – удаление файлов с атрибутом «только для чтения»;
- /S – удаление указанного файла из всех вложенных папок;
- /Q – удаление без запроса на подтверждение ;
- S — Системные;
- H — Скрытые;
- R – Только для чтения;
- A — Для архивирования
- Также перед атрибутами можно использовать знак минус «-», который имеет значение «НЕ». Например, «-S» означает не системный файл.
Обычно, для того чтобы воспользоваться командной DEL нужно сначала перейти в папку, в которой находится файл для удаления, и после этого выполнить команду. Для того чтобы сменить диск нужно просто ввести букву диска и двоеточие. А для перемещения по папкам нужно использовать команду « CD ».
После того как вы попали в нужную папку можно приступать к удалению файлов. Для этого просто введите команду DEL и название файла.
Также, при необходимости вы можете удалять файлы, не перемещаясь по папкам. В этом случае нужно указывать полный путь к документу.
Если есть необходимость выполнить запрос на подтверждение удаления каждого их файлов, то к команде DEL нужно добавить параметр « /p ». В этом случае в командной строке будет появляться запрос на удаление файла и пользователю нужно будет ввести букву «Y» для подтверждения.
Нужно отметить, что при использовании параметра «/a», отвечающие за атрибуты буквы нужно вводить через двоеточие. Например, для того чтобы удалить все файлы с атрибутом «только для чтения» и с расширением «txt» нужно ввести команду « del /F /A:R *.txt ».
Аналогичным образом к команде DEL можно добавлять и другие параметры. Комбинируя их вы сможете создавать очень мощные команды для удаления файлов через командную строку Windows. Ниже мы приводим еще несколько примеров:
- del D:\ — уничтожение всех файлов в корне диска D;
- del D:\*.txt – уничтожение всех файлов с расширением txt в корне диска D;
- del D:\doc – уничтожение всех файлов в папке d:\doc (документы с атрибутами будут пропущены);
- del /A:r d:\doc\*.txt – уничтожение всех файлов с атрибутом «только для чтения» и расширением «txt» в папке d:\doc;
Удаление папок через командную строку
Если вам нужно удалить папку через командную строку Windows, то указанные выше команды вам не помогут. Для удаления папок существует отдельная команда RD или RMDIR (сокращение от английского Remove Directory).
Команды RD и RMDIR являются синонимами и предназначены для удаления папок. Они могу принимать следующие параметры:
- /S — удаление всего дерева каталогов, при использовании данного параметра будет удалена не только сама папка, но и все ее содержимое;
- /Q – удаление дерева папок без запроса на подтверждение;
Например, для того чтобы удалить папку достаточно ввести команду RD и название папки.
Если папка содержит вложенные папки или файлы, то при ее удалении будет выведена ошибка».
Для решения этой проблемы к команде RD нужно добавить параметр « /s ». В этом случае удаление проходит без проблем, но появляется запрос на подтверждение удаления.
Для того чтобы удаление дерева папок прошло без появления запроса на подтверждение к команде нужно добавить параметр « /q ». В этом случае папка удаляется без лишних вопросов.
Также команда RD может принимать сразу несколько папок, для этого их нужно просто разделить пробелом. Например, если выполнить « rd 111 222 », то за один раз можно удалить папки с названиями « 111 » и « 222 ».
Если же вам нужно удалить через командную строку папку, которая сама содержит пробел, то в этом случае ее название нужно взять в двойные кавычки.
Комбинируя команды DEL и RD , можно создавать мощные скрипты для очистки и удаления папок в операционной системе Windows.
cmd Delete Folder – How to Remove Files and Folders in Windows
Kris Koishigawa
Sometimes it’s just faster to do things with the command line.
In this quick tutorial we’ll go over how to open Command Prompt, some basic commands and flags, and how to delete files and folders in Command Prompt.
If you’re already familiar with basic DOS commands, feel free to skip ahead.
How to open Command Prompt
To open Command Prompt, press the Windows key, and type in «cmd».
Then, click on «Run as Administrator»:
After that, you’ll see a Command Prompt window with administrative privileges:
Screenshot of Command Prompt window
If you can’t open Command Prompt as an administrator, no worries. You can open a normal Command Prompt window by clicking «Open» instead of «Run as Administrator».
The only difference is that you may not be able to delete some protected files, which shouldn’t be a problem in most cases.
How to delete files with the del command
Now that Command Prompt is open, use cd to change directories to where your files are.
I’ve prepared a directory on the desktop called Test Folder. You can use the command tree /f to see a, well, tree, of all the nested files and folders:
To delete a file, use the following command: del » » .
For example, to delete Test file.txt , just run del «Test File.txt» .
There may be a prompt asking if you want to delete the file. If so, type «y» and hit enter.
Note: Any files deleted with the del command cannot be recovered. Be very careful where and how you use this command.
After that, you can run tree /f to confirm that your file was deleted:
Also, bonus tip – Command Prompt has basic autocompletion. So you could just type in del test , press the tab key, and Command Prompt will change it to del «Test File.txt» .
How to force delete files with the del command
Sometimes files are marked as read only, and you’ll see the following error when you try to use the del command:
To get around this, use the /f flag to force delete the file. For example, del /f «Read Only Test File.txt» :
How to delete folders with the rmdir command
To delete directories/folders, you’ll need to use the rmdir or rd command. Both commands work the same way, but let’s stick with rmdir since it’s a bit more expressive.
Also, I’ll use the terms directory and folder interchangeably for the rest of the tutorial. «Folder» is a newer term that became popular with early desktop GUIs, but folder and directory basically mean the same thing.
To remove a directory, just use the command rmdir .
Note: Any directories deleted with the rmdir command cannot be recovered. Be very careful where and how you use this command.
In this case I want to remove a directory named Subfolder, so I’ll use the command rmdir Subfolder :
But, if you remember earlier, Subfolder has a file in it named Nested Test File.
You could cd into the Subfolder directory and remove the file, then come back with cd .. and run the rmdir Subfolder command again, but that would get tedious. And just imagine if there were a bunch of other nested files and directories!
Like with the del command, there’s a helpful flag we can use to make things much faster and easier.
How to use the /s flag with rmdir
To remove a directory, including all nested files and subdirectories, just use the /s flag:
There will probably be a prompt asking if you want to remove that directory. If so, just type «y» and hit enter.
And that’s it! That should be everything you need to know to remove files and folders in the Windows Command Prompt.
All of these commands should work in PowerShell, which is basically Command Prompt version 2.0. Also, PowerShell has a bunch of cool aliases like ls and clear that should feel right at home if you’re familiar with the Mac/Linux command line.
Did these commands help you? Are there any other commands that you find useful? Either way, let me know over on Twitter.
Kris Koishigawa
Read more posts by this author.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.