0

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).

TheNewBoy
  • 3
  • 2
  • 3
    bash and batch-file are completely unrelated, so in what environment are you trying to accomplish this? Welcome as a new user to [SO]. Please take the [tour] and also read [ASK]. SO isn't a free script writing service nor a forum, but a site for programmers helping colleagues who got stuck with a distinct problem. Own research and serious coding attempts are expected. [Edit] the question to include **your** code in a [mcve]. –  Jun 04 '19 at 09:03

2 Answers2

1

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"
    )
)
aschipfl
  • 33,626
  • 12
  • 54
  • 99
0

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>\
Dominique
  • 16,450
  • 15
  • 56
  • 112
  • Deleting and recreating files is not the same as keeping them, because attributes get lost (e. g., creation date, owner, etc.); so the questioner has to decide whether or not this is acceptable... – aschipfl Jun 04 '19 at 19:25