Compare directory name to string

放肆的年华 提交于 2020-01-17 08:36:29

问题


I've created this very simple batch file for the sake of testing a concept I'm hoping to utilize. I need to recursively delete all of one type of file except in folders with a specific name. Here's my code:

:recur
FOR /f %%a IN ('DIR /b') DO (
IF EXIST %%a\NUL (
    IF ["%%a" NEQ "subtest2"] (
        ECHO %%a
        CD %%a
        CALL :recur
        CD ..
    )
)
COPY "*.cfm" "*_copy.cfm"
REM DEL "*_copy*.cfm"
)

Right now I'm just testing using copy instead of delete. Basically, this should create a copy of all the .cfm files except in the folder "subtest2". Right now it's recursively making the copies everywhere, including subtest2. How do I stop this?

The structure of my base directory is:

TestFolder
---subtest1
------test.pdf
------test.txt
------test.cfm
---subtest2
------test.pdf
------test.txt
------test.cfm
---test.pdf
---test.txt
---test.cfm
---recur.bat


回答1:


The square brackets are not balanced on both sides of the IF comparison, so it can never match. The brackets are not part of the IF syntax. If present, they simply become part of the string that is compared. The same is true for any enclosing quotes. Remove the square brackets, and it will work (assuming there are no other problems)

Here is a simple method to accomplish your goal. I've prefixed the DEL command with ECHO for testing purposes:

for /r /d %%F in (*) do echo %%F\|findstr /liv "\\subtest2\\" >nul && echo del "%%F\*.cfm"

The FOR /R /D simply recurses all folders. The full path of each folder is piped into a FINDSTR command that looks for paths that do not contain a \subtest2 folder. The ECHO DEL command is only executed if the \subtest2\ folder is not found in the path.

Remove the last ECHO when you have confirmed the command gives the correct results.

Change %%F to %F if you want to run the command on the command line instead of in a batch file.




回答2:


for f in `find . -path YOURDIR -prune -o print`
  do
    rm whateveryouwanttodelete
  done

the find command in backticks finds all files but ignores the directory -prune you want to ignore. Then in the body of the loop you nuke the files. You can do even better with

find . -path YOURDIR -prune -o -print0 | xargs -0 rm -f

no need for the loop. DISCLAIMER: I haven't tested it so perhaps you want to start adopting it with cp instead of rm.




回答3:


You can try this:

@echo off&setlocal
for /r /d %%i in (*) do (
    pushd "%%i"
    echo(%%i|findstr /ri "\\subtest2$" || COPY "*.cfm" "*_copy.cfm"
    popd
)


来源:https://stackoverflow.com/questions/16819972/compare-directory-name-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!