简体   繁体   中英

Windows equivalent find -delete

What is the Windows/DOS equivalent to this Linux command?

find . -path "*/migrations/*.py" -not -name "__init__.py" -delete

I know how to delete all the files but not how to specify an exception (ie: not deleting __init__.py )

cmd.exe doesn't support wildcards in several levels of a path (PowerShell does) so you've to emulate this somehow.

Cmd line:

for /f "delims=" %F in ('Dir /B /S .\*.py ^|findstr /IE "\\migrations\\[^\\]*.py"^|findstr /IEV "\\__init__.py" ') Do @echo del "%F"

If the output looks OK, remove the echo
In a batch file double the percent signs %F => %%F

PowerShell

Get-ChildItem .\*\migrations\*.py -exclude __init__.py | Remove-Item -WhatIf

If the output looks OK, remove the -WhatIf

In this sample tree

> tree /F
A:.
└───test
    │   alpha.py
    │   bravo.py
    │
    └───migrations
            alpha.py
            bravo.py
            __init__.py

the output will be

del "A:\test\migrations\alpha.py"
del "A:\test\migrations\bravo.py"

WhatIf: Ausführen des Vorgangs "Datei entfernen" für das Ziel "A:\test\migrations\alpha.py".
WhatIf: Ausführen des Vorgangs "Datei entfernen" für das Ziel "A:\test\migrations\bravo.py".

Exceptions are not possible (as far as I know) in Windows/DOS search, but they are possible in xcopy /exclude and robocopy /X... . Therefore I'd advise you to copy all but the exceptions to a kind of backup folder, remove all the original ones (including the exceptions) and put everything back.

You can probably use for /R and if , something like this:

for /r %i in (*.py) do (
  if "%~ni"=="__init__" (
    echo Skipping %i
  ) else (
    echo del "%i"
  )
)

Here I've prefixed the del command with echo so it doesn't actually delete it. Once it looks like it's doing what you want, then take away that echo.

If you do this in a batch file, you'll need to double up the % signs.

The for /R is a recursive for, and in that format will work from the current directory.

The %~ni says "give me the filename part only, of %i"

(I'm running Linux at the moment so I can't verify exact behaviour, but you could start with this).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM