Reputation: 3
SO basically, lets say I have an example folder as following:
C:\
└───Dox
│ cat.txt
│ dog.txt
│ girl.txt
│ ...
│
└───NonDOx
boy.txt
girl.txt
...
I want it to look like this,
C:\
└───Dox
│ girl.txt
│
└───NonDOx
girl.txt
So, yeah basically, all the files from folder and sub-folder should be deleted, except girl.txt
, which lies in random folders.
Also , what is the difference between folder and a directory? Is it like a
directory is a folder that has one or more folders in it or its just same as folder?
I couldn't find something that would delete in sub folders and leave 1(particular file).
Upvotes: 0
Views: 458
Reputation: 17479
The simpliest (and most secure) way to remove all but ..., is by copying only those files to a backup folder, remove the whole original directory, and put the backed up files back. The reason that I call this secure, it that you can check in the backup directory if all needed files are there: (not tested)
xcopy /S girl.txt <Backup_Directory>\
cd <Backup_Directory>
tree /F //verify if everything is well copied
rmdir <original_directory>
xcopy /S <Backup_Directory>\ <original_directory>\
Upvotes: 0
Reputation: 34909
I would do it the following way:
rem /* Loop over all items (both files and sub-directories) in the root directory recursively;
rem then sort them in reverse alphabetic manner, so lower directory hierarchy levels appear
rem before higher ones and files appear before their parent sub-directories: */
for /F "delims= eol=|" %%F in ('dir /S /B /A "C:\Dox\*.*" ^| sort /R') do (
rem // Check whether current item is a file (note the trailing `\` to match directories):
if not exist "%%F\" (
rem // The current item is a file, hence check its name and delete if not matching:
if /I not "%%~nxF" == "girl.txt" del "%%F"
) else (
rem // The current item is a sub-directory, hence try to remove it; this only works
rem when it is empty; the `2> nul` prefix suppresses potential error messages:
2> nul rd "%%F"
)
)
Upvotes: 1