Deleting directories using single liner command
rm -r edi edw
rm
can take an arbitrary number of arguments, and the -r
flag makes it delete directories recursively. Refer to man rm
for more details.
Reading manual pages are the best way to get information for your questions.
How to delete files/subfolders in a specific directory at the command prompt in Windows
You can use this shell script to clean up the folder and files within C:\Temp
source:
del /q "C:\Temp\*"
FOR /D %%p IN ("C:\Temp\*.*") DO rmdir "%%p" /s /q
Create a batch file (say, delete.bat) containing the above command. Go to the location where the delete.bat file is located and then run the command: delete.bat
Delete multiple directories with a single batch file
for %%a in ("dirname 1" "dirname2" "as many as you want") do rd /s /q "%%~a"
should do what you want - %%a is set to each [optionally-quoted] argument in turn. You Must use the quotes if the directoryname contains separators like spaces.
Delete a directory and its files using command line but don't throw error if it doesn't exist
Redirect the output of the del
command to nul. Note the 2
, to indicate error output should be redirected. See also this question, and especially the tech doc Using command redirection operators.
del {whateveroptions} 2>null
Or you can check for file existence before calling del
:
if exist c:\folder\file del c:\folder\file
Note that you can use if exist c:\folder\
(with the trailing \
) to check if c:\folder
is indeed a folder and not a file.
Need windows batch command one-liner to remove folders by name, not by date.time using powershell if applicable
The PowerShell code for this would be:
Get-ChildItem -Path 'RootPath\Where\The\Folders\To\Delete\Are\Found' -Filter '*_*_*' -Directory |
Where-Object { $_.Name -match '\d{2}_\d{2}_\d{4}' } | # filter some more using regex -match
Sort-Object { [datetime]::ParseExact($_.Name, 'MM_dd_yyyy', $null) } | # sort by date
Select-Object -SkipLast 7 | # skip the newest 7 folders
Remove-Item -Recurse -Force # remove the rest
To play it safe, add -WhatIf
to the final Remove-Item
command. By doing that, the code does not actually delete anything, but show in the console what would be deleted. If you are satisfied that is correct, then remove -WhatIf
to actually remove those folders.
As Olaf already commented, don't think using one-line code would be best, because what you'll end up with is code that isn't readable anymore and where mistakes are extremely hard to find.
There is no penalty whatsoever for multiline code, in fact it is THE way to go!
How to delete a folder and all contents using a bat file in windows?
@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"
Explanation:
Removes (deletes) a directory.
RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path
/S Removes all directories and files in the specified directory
in addition to the directory itself. Used to remove a directory
tree.
/Q Quiet mode, do not ask if ok to remove a directory tree with /S
CMD to delete a specific folder with files from multiple folder paths
First, as explained by the Microsoft documentation Naming Files, Paths, and Namespaces, the directory separator on Windows is \
and not /
as on Linux/Mac. /
is used on Windows for options as you can see on your code for example on /Q
. So use in future \
in file/folder paths. The Windows file system accessing kernel functions automatically replace all forward slashes by backslashes before accessing the file systems, but writing code depending on automatic error correction is never a good idea.
The task to delete all folders with name log
or log-archive
in a specified folder and all its subfolders can be done with a single command line.
@for /F "delims=" %%I in ('dir "%ProgramFiles%\product\plugins\plugin_Path\log*" /AD /B /S 2^>nul ^| %SystemRoot%\System32\findstr.exe /E /I /R "\\log \\log-archive"') do @rd /Q /S "%%I" 2>nul
FOR with option /F
runs in a separate command process started with cmd.exe /C
(more precise with %ComSpec% /C
) in background the command line in '
... '
which is here:
dir "C:\Program Files\product\plugins\plugin_Path\log*" /AD /B /S 2>nul | C:\Windows\System32\findstr.exe /E /I /R "\\log \\log-archive"
The command DIR outputs to handle STDOUT
- in bare format because of option
/B
- just directories because of option
/AD
(attribute directory) - directory names matching the wildcard pattern
log*
- in specified directory
C:\Program Files\product\plugins\plugin_Path
- and all its subdirectories because of option
/S
- with full path also because of option
/S
.
It could be that DIR does not find any file system entry matching these criteria. In this case an error message is output by DIR to handle STDERR. This error output is redirected with 2>nul
to device NUL to suppress it.
The standard output of DIR is redirected with |
to handle STDIN of FINDSTR which runs
- because of option
/I
a case-insensitive - regular expression find explicitly requested with option
/R
- for string
\log
or\log-archive
(space is interpreted as OR) - which must be found at end of a line because of option
/E
.
All lines matching these search criteria are output by FINDSTR to handle STDOUT of background command process. This filtering of output of DIR with FINDSTR is necessary to avoid the deletion of a directory which is named for example LogToKeep
also found and output by DIR.
Read the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul
and |
. The redirection operators >
and |
must be escaped with caret character ^
on FOR command line to be interpreted as literal characters when Windows command interpreter processes this command line before executing command FOR which executes the embedded command line with using a separate command process started in background.
FOR with option /F
captures output to handle STDOUT of started command process and processes this output line by line after started cmd.exe
terminated itself. Empty lines are always ignored by FOR which do not occur here. Lines starting with a semicolon are also ignored by default because of eol=;
is the default definition for end of line option. But a full qualified folder path cannot contain a semicolon at beginning because the folder path starts either with a drive letter or with a backslash in case of a UNC path. So default end of line option can be kept in this case. FOR would split up by default every line into substrings with using normal space and horizontal tab as string delimiters and would assign just first space/tab separated string to specified loop variable. This line splitting behavior is not wanted here as the folder path contains definitely a space character and the entire folder path is needed and not just the string up to first space. For that reason delims=
is used to specify an empty list of delimiters which disables line splitting behavior.
FOR executes for every directory output by DIR passing FINDSTR filter with full path the command RD to remove the directory quietly because of option /Q
and with all files and subdirectories because of /S
.
The deletion of the directory could fail because of missing NTFS permissions, or the directory to delete or one of its subdirectories is current directory of a running process, or a file in the directory to delete is currently opened by a running process in a manner which denies deletion of the file while being opened, or the directory to delete does not exist anymore because it was deleted already before in FOR loop. The error message output by command RD to handle STDERR is in this case redirected to device NUL to suppress it.
Please note that command RD deletes all log
and log-archives
directories and not just the files and subdirectories in these directories. It is unclear from your question what exactly should be deleted by the batch file.
It is of course also possible to replace rd /Q /S "%%I"
by del /A /F /Q "%%I\*"
to delete just all files including hidden and read-only files quietly in the directory assigned with full path to loop variable I
.
@
left to command FOR and command RD just suppress the output of those commands before execution by Windows command processor cmd.exe
. Both @
are not needed if this single command line is used in a batch file containing before @echo off
.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
dir /?
findstr /?
for /?
rd /?
Delete all files and folders in a directory
del *.*
instead of del *.db
. That will remove everything.
How to delete the contents of a folder?
import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
Related Topics
Running Meteor Application on a Single Core
Execute External Program with Trigger in Postgres 9.4
Why Does 'Ping' Not Timeout in Linux
When Did Hup Stop Getting Sent and What How to Do About It
Kill Bash Script Foreground Children When a Signal Comes
Generate Disk Usage Graphs/Charts with Cli Only Tools in Linux
What Are Coding Conventions for Using Floating-Point in Linux Device Drivers
How to Tell Linux to Keep a Page and Not Evict It
Linux Kernel Code in Memory Check with Sha256 Sum
Difference Between Archiving and Compression
Compile Errors Using Bfd.H on Linux
How to Rename a Shared Library to Avoid Same-Name Conflict
Remote Linux Server to Remote Linux Server Large Sparse Files Copy - How To
Kate Text Editor Cannot Handle Lines Longer Than 1024
Getting Uptime or Downtime of Systemd Process Using Systemctl