How to remove folders with a certain name
If the target directory is empty, use find, filter with only directories, filter by name, execute rmdir:
find . -type d -name a -exec rmdir {} \;
If you want to recursively delete its contents, replace -exec rmdir {} \;
with -delete
or -prune -exec rm -rf {} \;
. Other answers include details about these versions, credit them too.
How to delete all subdirectories with a specific name
If find
finds the correct directories at all, these should work:
find dir -type d -name "subdir1" -exec echo rm -rf {} \;
or
find dir -type d -name "subdir1" -exec echo rm -rf {} +
(the echo
is there for verifying the command hits the files you wanted, remove it to actually run the rm
and remove the directories.)
Both piping to xargs
and to while read
have the downside that unusual file names will cause issues. Also, find -delete
will only try to remove the directories themselves, not their contents. It will fail on any non-empty directories (but you should at least get errors).
With xargs
, spaces separate words by default, so even file names with spaces will not work. read
can deal with spaces, but in your command it's the unquoted expansion of $tar
that splits the variable on spaces.
If your filenames don't have newlines or trailing spaces, this should work, too:
find ... | while read -r x ; do rm -rf "$x" ; done
Delete content of all folders with certain name
To get the *
in -exec rm -r "{}/*"
expanded you would need to run a shell instead of executing rm
directly, but with this option you must be careful not to introduce a command injection vulnerability. (see https://unix.stackexchange.com/a/156010/330217)
Another option is to use -path
instead of -name
find . -path '*/build/*' -exec rm -r "{}" \; -prune
Option -prune
is to avoid descending into a directory that has been removed before.
How to delete folders with specific names in Python?
After some time of practising, I ended up with a code that was in my mind:
def create_folders(zoom):
zoom_min = 1
path_to_folders = 'D:/ms_project/'
if os.path.isdir(path_to_folders):
if not os.listdir(path_to_folders) == []:
for subfolder in os.listdir(path_to_folders):
subfolder_path = os.path.join(path_to_folders, subfolder)
try:
if os.path.isdir(subfolder_path):
shutil.rmtree(subfolder_path)
elif os.path.isfile(subfolder_path):
os.unlink(subfolder_path)
except Exception as e:
print(e)
elif os.listdir(path_to_folders) == []:
print("A folder existed before and was empty.")
elif not os.path.isdir(path_to_folders):
os.mkdir("ms_project")
os.chdir(path_to_folders)
for name in range(zoom_min, zoom + 1):
path_to_folders = '{0}'.format(name)
if not os.path.exists(path_to_folders):
os.makedirs(path_to_folders)
Thanks to everyone who inspired me, especially who replied me to my initial question.
How to delete all folders with a specific name using powershell
Pipeline objects need to be referenced with $_
, not $
, as shown below:
Get-Childitem -Path C:\folder1 -Recurse | Where-Object {$_.Name -ilike "*tempspecssuite*"} | Remove-Item -Force -WhatIf
Which can also be referenced with $PSItem
or set to a custom variable with the -PipelineVariable
common parameter. You can find out more in about_pipelines
,about_objects
and about_automatic_variables
.
You could also simplify the above by making use of the -Filter
parameter from Get-ChildItem
, which also accepts wildcards:
Get-ChildItem -Path C:\folder1 -Directory -Filter tempspecssuite_* -Recurse | Remove-Item -Force -Recurse -WhatIf
Which allows Get-ChildItem
to filter files while they are getting retrieved, rather than filtering with Where-Object
afterwards.
You can also limit the filtering with the -Directory
switch, since we only care about deleting directories.
Delete Folder and contents with contains specific name
From my comment, the following should show you all of the directories in C:\Documents
which have names beginning with System_This_Computer
and have not been modified in the last 10
days.
ForFiles /P "C:\Documents" /M "System_This_Computer*" /D -10 /C "Cmd /C If @isdir==TRUE Echo @path"
Once you are satisfied with the output, change Echo
to RD /S/Q
to actually remove them.
How to remove all folders of name x within a directory using cmd/batch file
Here is another solution for this commented to describe each part of the script:
@Echo OFF
REM Important that Delayed Expansion is Enabled
setlocal enabledelayedexpansion
REM This sets what folder the batch is looking for and the root in which it starts the search:
set /p foldername=Please enter the foldername you want to delete:
set /p root=Please enter the root directory (ex: C:\TestFolder)
REM Checks each directory in the given root
FOR /R %root% %%A IN (.) DO (
if '%%A'=='' goto end
REM Correctly parses info for executing the loop and RM functions
set dir="%%A"
set dir=!dir:.=!
set directory=%%A
set directory=!directory::=!
set directory=!directory:\=;!
REM Checks each directory
for /f "tokens=* delims=;" %%P in ("!directory!") do call :loop %%P
)
REM After each directory is checked the batch will allow you to see folders deleted.
:end
pause
endlocal
exit
REM This loop checks each folder inside the directory for the specified folder name. This allows you to check multiple nested directories.
:loop
if '%1'=='' goto endloop
if '%1'=='%foldername%' (
rd /S /Q !dir!
echo !dir! was deleted.
)
SHIFT
goto :loop
:endloop
You can take the /p
out from in front of the initial variables and just enter their values after the =
if you don't want to be prompted:
set foldername=
set root=
You can also remove the echo
in the loop portion and the pause
in the end portion for the batch to run silently.
It might be a little more complicated, but the code can be applied to a lot of other uses.
I tested it looking for multiple instances of the same foldername qwerty
in C:\Test
:
C:\Test\qwerty
C:\Test\qwerty\subfolder
C:\Test\test\qwerty
C:\Test\test\test\qwerty
and all that was left was:
C:\Test\
C:\Test\test\
C:\Test\test\test\
Powershell delete subfolders with a specific name
You are almost there. No need to use quotes around $cookies
.
If you do a foreach ($cookie in $cookies)
, then operate on $cookie
in the script block, not $cookies
.
This works:
$cookies = Get-ChildItem \\myserver\test\User\Profiles\*\AppData\Roaming\Microsoft\Windows\Cookies
foreach ($cookie in $cookies){
Remove-Item $cookie -Force -Recurse -ErrorAction SilentlyContinue
}
but this will work as well, without a loop:
$cookies = Get-ChildItem \\myserver\test\User\Profiles\*\AppData\Roaming\Microsoft\Windows\Cookies
Remove-Item $cookies -Force -Recurse -ErrorAction SilentlyContinue
If you want a one-liner and no variables:
Get-ChildItem \\myserver\test\User\Profiles\*\AppData\Roaming\Microsoft\Windows\Cookies | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
How to delete files AND folders with specific names, and all of the files within those folders with Java
You can use Apache Commons IO FileUtil (or at least have a look at the source) instead of File.delete():
FileUtil.deleteDirectory(newDirectoryStreamItem);
You can’t use delete() (naively) since you recursively need to delete the content of a subdir before deleting the directory itself.
Related Topics
How Do 2 or More Fork System Calls Work
Shell Script to Kill the Process Listening on Port 3000
Differencebetween Ld_Library_Path and -L at Link Time
Maximum Number of Files/Directories on Linux
What Is the Use of _Iomem in Linux While Writing Device Drivers
How to Test If Your Linux Support Sse2
Does The Bios Copy The 512-Byte Bootloader to 0X7C00
All Newlines Are Removed When Saving Cat Output into a Variable
Does The Linux Scheduler Needs to Be Context Switched
Distributing Binary Applications Across Linux Distros
Diolan Dln-2 Spi Controller on X86_64 Platform
How to Figure Out What Is Using a Linux Kernel Module
What Is a Way to Read Man Pages in Vim Without Using Temporary Files
How to Install Maven on Redhat Linux
Avrisp Mkii Doesn't Work with Avrdude on Linux