Skip to main content

Delete Directories with Wildcards using rd or rmdir

 
Deleting files in command prompt using wildcards is quite straight forward.

Command below will delete all text (".txt") files on the specified path.

     Del D:\txtlog\*.txt

Command above will delete all files with ".txt" extension in d:\txtlog directory.

Easy enough to delete all matching files.

Using the same method with rmdir or rd command this will not work.


For example, if we have a directory on d drive that is auto-generated by an application and the filename is consistent with a pattern plus incrementing number at the end to differentiate the folder from other folders.


   D:\baklogs\log1\
   D:\baklogs\log2\
   D:\baklogs\log3\
   Etc..
   D:\baklogs\log100\


The folder name has a consistent pattern that is preceded by the word “log” plus incrementing number.

If the command below is executed to remove the directories in one go, an error is shown which has this message: "The filename, directory name, or volume label syntax is incorrect."

rmdir D:\baklogs\log* /s
rd D:\baklogs\log* /s
/s - recursive deletion all folders and subfolders


The method above will result in an error because the command interprets the input literally, the command is looking for a folder with this folder name "log*".


Deletion of directories using wildcard can be done with some twist.

In order to remove a directory, a complete path is needed as input to rmdir or rd command.
Input requirements of "RD" or "RMDIR" command can be meet, using Dir command and the right use of its parameters.

Dir command which lists files and folders and provides an option to display the folder in a complete path.

     dir /a:d /s /b l* 

Command above will display directories that start with letter "l" including its path.

Example:
   D:\baklogs\log1\lrx

   D:\baklogs\log2\lrb

   D:\baklogs\log3\lbr

The input requirement for rd or rmdir command is completed using the dir command.
In order to delete all the directories that match the wildcard; for loop is needed and supplied to the rd or rmdir command.


Here's the script that will do the job.

   for /f %i in ('dir /a:d /s /b l*') do echo rd /s /q "%i"

That's it a dir command and for loop will be able to delete directories recursively using wildcards.
Above command uses "echo" to show the directories that will be deleted.


Removing the "echo" will permanently remove all the directories that match the wildcard, before removing ”echo” pray hard that you're doing the right thing.
 
Editing above code from comments below, if above command doesn't work.
 
for /f  %%i in ('dir /a:d /s /b l*') do echo rd /s /q "%%i"
 
for /f "delims=''" %i in ('dir /a:d /s /b l*') do echo rd /s /q "%i" 
 
"<< double quotes delims=' <<single quote '<<single quote "<<double quotes 
 
Thank you guys for the comment, I have edited the post based on your response for others who might stumble same issue. :) 


Cheers..till next time :)

================================
Free Android Apps:

Click on links below to find out more:

Linux Android App cheat sheet:
https://play.google.com/store/apps/details?id=com.LinuxMobileKit
 

https://play.google.com/store/apps/details?id=soulrefresh.beautiful.prayer

Catholic Rosary Guide  for Android:

https://play.google.com/store/apps/details?id=com.myrosaryapp

http://quickbytesstuff.blogspot.sg/2014/09/how-to-recite-rosary.html

Divine Mercy Chaplet Guide (A Powerful prayer):

https://play.google.com/store/apps/details?id=com.dmercyapp


Comments

  1. does not work if the folder name contains spaces

    ReplyDelete
  2. does not work if the folder name contain spaces

    ReplyDelete
    Replies
    1. it should work "%i" <-- do not remove the "quotes" in %i.

      Delete
    2. it took me a long time to figure this out with spaces. Simply including quotes around %i is not enough. you must use "delims=''"

      Delete
  3. How can you get this to work in a batch or cmd file?

    ReplyDelete
    Replies
    1. for /f %i in ('dir /a:d /s /b l*') do echo rd /s /q "%i" <-- open notepad and save this command as ".bat" or ".cmd", when using "save as" in notepad do it like this: "delete_dirs.bat" or "delete_dirs.cmd" enclose the filename and file extension in quotes, if no quotes the file will be saved as ".txt", remove the "echo" if you are happy with the result.

      Delete
  4. Hello,thank you for your nice tip!
    I applied your examples in my batch script, but I have some trouble with running the script successfully.

    During the execution of script, it stopped the whole script with this error message.

    /s was unexpected at this time. Several googling didn't help to find cause and solution.
    I would appreciate if I get some advice from you.

    Here are the my script.

    @echo off
    rem Delete Directories with Wildcards using rd or rmdir
    for /f %i in ('dir /a:d /s /b s:\temp\TCD*') do rd /s /q "%i"
    for /f %i in ('dir /a:d /s /b s:\temp\*tmp') do rd /s /q "%i"
    for /f %i in ('dir /a:d /s /b s:\temp\hnc*') do rd /s /q "%i"
    for /f %i in ('dir /a:d /s /b s:\temp\hwp*') do rd /s /q "%i"
    for /f %i in ('dir /a:d /s /b s:\temp\~*') do rd /s /q "%i"
    rem https://quickbytesstuff.blogspot.com/2016/06/delete-directories-with-wildcards-using.html

    Thank you for hearing me and reading this!

    ReplyDelete
    Replies
    1. Hello BNSoenar,

      You don't need to specify the path.

      Example: for /f %i in ('dir /a:d /s /b s:\temp\TCD*') do rd /s /q "%i" (your command as written above)
      use this one instead:
      cd s:\temp\
      then do:
      for /f %i in ('dir /a:d /s /b TCD*') do rd /s /q "%i"

      basically, you manually cd to the path then execute the batch file as written on the blog example

      Good luck, hope it helps.

      Delete
    2. Sirch, I really appreciate your advice.
      Unfortunately, that fix doesn't work for my case.
      I removed all s:\temp\ and added "cd s:\temp\", but result was the same.
      So I tried one test run for experiment for your help.

      Below is the result of experiment.
      -----------------------------------------------------------------------------------
      J:\Residenz\Auxiliary>instant_sleep_for_fans_modu_temp_cleaner
      /s was unexpected at this time.

      J:\Residenz\Auxiliary>for /f %i in ('dir /a:d /s /b TCD*') do rd /s /q "%i"
      File Not Found

      J:\Residenz\Auxiliary>for /f "%i" in ('dir /a:d /s /b TCD*') do rd /s /q "%i"
      in was unexpected at this time.
      -----------------------------------------------------------------------------------

      "/s was unexpected" is shown when that command was executed in batch file only.
      Running the command in command line did not make any errors.
      "in was unexpected" is shown when I add quotation marks at the first "%i.

      Delete
    3. J:\Residenz\Auxiliary>for /f %i in ('dir /a:d /s /b TCD*') do rd /s /q "%i"
      File Not Found

      in s:\temp\ are there files that starts with TCD*?

      If there is none just replace it with any characters that you want to remove, be careful though as it will delete any matching files and I think rd is also subject to the 255 path limitation

      Delete
    4. Sorry for my poor English (I am not a native speaker).

      "File not Found" was just an my example that the "For" command was successfully executed.
      In other words, if the "For" command was accidentally halted with the "... was unexpected", then "File Not Found" message could not show up.
      Please ignore about the "File Not Found" message and path, I can handle those errors.
      (In addition, I'm pretty sure that path would not exceed 255. That is because those names are S:\temp\TCDBC9B.tmp, and S:\temp\TCDB63A.tmp ... that's all. total 11 strings after S:\temp. Period in the folder name can cause a problem?)

      As you can see the third example (intentionally inserted "" strings) in my experiment, the error message is very similar to the first example's error. From both cases, it seems to be that some parameters could not be correctly transferred to "For" command when the command is executed in batch script.

      Do you have any insight for my symptoms? Thank you for hearing me.

      Delete
    5. Quite hard to explain how the batch file works in the background, but if you are interested in creating your own application from scratch so you will know exactly what the program is doing; see this project in Github: https://github.com/RickStrahl/DeleteFiles
      aside from this you can always create your own application in any programming language you are well verse at.

      Delete
    6. Thank you for recommendation.
      I'm not a developer and have no coding or languages experiences.
      I have just a experience with MS-DOS and familiar with editing batch files, that's all I can do. Making a program is not viable option for the present (If I can retire with sufficient money, I want to learn those).

      I looked into the program you recommended. Sadly, the program doesn't support wildcard folder deletion.

      And.. oh, I finally found solution during composing this comment, and I want share it with you.

      As I describe, I have no language experience, so I would appreciate if you provide some explanation how it works.

      ------Inspired from the following link ---------

      https://social.technet.microsoft.com/Forums/en-US/93fa823a-fcd2-4091-b5d0-d4ba6f69b2f1/remove-directory-using-wildcards?forum=w7itprogeneral

      -------------------------------------------------------

      From the link, I copy and pasted that code and I found the major difference between theirs and yours, the double percent sign!

      I changed your code and added one more percent sign, and the batch file works (showing File Not Found message).

      Thank you for your code template, Sirch. I have no idea why it work, anyway it works without error. Thank you.

      Delete
  5. I needed to make some tweaks for the script to delete folders whose folder names contain embedded blanks. Here's example code that works where I'm purging the entire contents of the Windows "Downloads" folder of all folders, subfolders, and contained files:

    rem ------------------------------------------------------------------------------------------------------------------------
    rem This Windows script purges the default Windows OS "Downloads" folder
    rem ------------------------------------------------------------------------------------------------------------------------

    rem [Step 1]: Go to the Downloads folder
    cd "C:\Users\%username%\Downloads"

    rem [Step 2]: Delete *all* files in the "Downloads" folder tree
    del /s /f /q .\*

    rem [Step 3]: Delete *all* folders in the "Downloads" folder tree
    for /d %%i in (.\*) do rmdir /s /q "%%i"

    rem End of script
    .

    ReplyDelete
    Replies
    1. What's the error you encounter when running the above script when it encounters an embedded blank folder?

      Delete

Post a Comment

Popular posts from this blog

Notepad++ convert multiple lines to a single line and vice versa

Notepad++ is an awesome text editing tool, it can accept regex to process the text data. If the data is in a “.csv” format or comma separated values which is basically just a text file that can either be opened using a text editor, excel or even word. Notepad++ can process the contents of the file using regex. Example if the data has multiple rows or lines, and what is needed is to convert the whole lines of data into a single line. Notepad++ can easily do it using regex. However, if the data is on a single line and it needs to be converted into multiple lines or rows then regex can also be used for this case. Here’s an example on how to convert multiple rows or lines into a single line. Example data: Multiple rows, just a sample data. Press Ctrl+H, and  on "Find what" type: [\r\n]+ and on "Replace with" type with: , (white space) --white space is needed if need to have a space in between the data. See image below, "Regular Expression" must be se

WMIC get computer name

WMIC get computer model, manufacturer, computer name and  username. WMIC is a command-line tool and that can generate information about computer model, its manufacturer, its username and other informations depending on the parameters provided. Why would you need a command line tool if there’s a GUI to check? If you have 20 or 100 computers, or even more. It’s quite a big task just checking the GUI to check the computer model and username. If you have remote computers, you need to delegate someone in the remote office or location to check. Or you can just write a batch file or script to automate the task. Here’s the code below on how get computer model, manufacturer and the username. Open an elevated command prompt and type:     wmic computersystem get "Model","Manufacturer", "Name", "UserName" Just copy and paste the code above, the word “computersystem” does not need to be change to a computer name. A

How to check office version from command line

The are quite a few ways to check office version it can be done via registry, PowerShell or VBScript and of course, good old command line can also do it. Checking Windows office version whether it is Office 2010, Office, 2013, Office 2016 or other version is quite important to check compatibility of documents; or just a part of software inventory. For PowerShell this simple snippet can check the office version: $ol = New-Object -ComObject Excel.Application $ol . Version The command line option will tell you where’s the path located; the result will also tell whether office is 32-bit, 64-bit and of course the version of the office as well. Here’s the command that will check the office version and which program directory the file is located which will tell whether it’s 32-bit or 64-bit. Command to search for Excel.exe: DIR C:\ /s excel.exe | find   /i "Directory of"  Above command assumes that program files is on  C: drive. Sample Outpu