【问题标题】:Jump inside a 'FOR' loop within a BATCH file跳入 BATCH 文件中的“FOR”循环
【发布时间】:2016-12-05 16:26:46
【问题描述】:

前段时间,我请求一些帮助来开发一个简短的批处理文件,以使用 7zip 压缩树内的文件,请参阅以下链接:

Compress separately files within subfolders

现在我想避免已经压缩的文件(.7z、.zip 文件)并跳转到下一个项目。

我还想删除以前在同一文件夹中多次使用原始批处理文件创建的压缩文件(如“.7z.7z”或“.zip.7z”)。 p>

这是我目前得到的:

@echo off
cd /d %~dp0
rem 7z.exe path
set sevenzip=
if "%sevenzip%"=="" if exist "%ProgramFiles(x86)%\7-zip\7z.exe" set sevenzip=%ProgramFiles(x86)%\7-zip\7z.exe

if "%sevenzip%"=="" if exist "%ProgramFiles%\7-zip\7z.exe" set sevenzip=%ProgramFiles%\7-zip\7z.exe

if "%sevenzip%"=="" echo 7-zip not found&pause&exit
@echo searching...
for /R %%I in (*) do (
        if not exist %%I.zip if not exist %%I.7zip "%sevenzip%" a -mx -mmt4 "%%I.7z" -r -x!*.bat "%%I" && "%sevenzip%" t "%%I.7z" * -r

)

del "Compressing_files_7zip.bat.7z"
del *.7z.7z*
del *.zip.7z*

::::::::::::::::::::::::::For setting up shutdown 60' after the end of the process.Remove colons in the line below.
::shutdown.exe /s /t 3600

pause

这段代码我遇到的主要问题是:

-我无法检测到已经压缩的文件,因此,跳转到下一个 %%I 实体。

-从子文件夹中删除不需要的过度压缩文件。显然,'*' 通配符在循环内不起作用;另一方面,如果我寻找 'del %%I.7z.7z' 它也不起作用。

我读到我不能为“if”循环使用正确的“OR”函数,这就是我嵌套它们的原因。

提前谢谢你。

亚历克斯。

【问题讨论】:

    标签: batch-file if-statement for-loop delete-file


    【解决方案1】:
    for /R %%I in (*) do (
            if not exist %%I.zip if not exist %%I.7zip "%sevenzip%" a -mx -mmt4 "%%I.7z" -r -x!*.bat "%%I" && "%sevenzip%" t "%%I.7z" * -r
    
    )
    

    请注意,%%I 将包含 complete 文件名,因此如果您找到 whatever.zip,则代码将查找whatever.zip**.zip** 或whatever.zip**.7zip ** 如果 这两个 都不存在,将执行7zip 并生成whatever.zip**.7z**

    因此,如果您找到 whichever.txt,则代码会查找 whichever.txt**.zip** 或 whichever.txt**.7zip** 并在 both 时执行 7zip其中不存在并生成 whichever.txt**.7z**

    我建议

    for /R %%I in (*) do (
      if not exist %%~nI.zip if not exist %%~nI.7z "%sevenzip%" a -mx -mmt4 "%%~nI.7z" -r -x!*.bat "%%I" && "%sevenzip%" t "%%~nI.7z" * -r
    
    )
    

    应该只选择文件名的name 部分。 (请参阅 docco 提示中的 for /?|more

    因此,代码将查找 whatever.zipwhatever.7z - 找到 whatever.zip 并且不执行 7zip

    或者,对于whichever.txt,代码将查找whichever.zipwhichever.7z - 两者都找不到并执行7zip 生成whichever.7z

    现在,由于存在whichever.7z,进一步的运行将跳过7zip

    这引发了一个问题 - 如果 zip/7z 存在,为什么不尝试更新存档,因为检测到的文件可能已更改?

    【讨论】:

    • 谢谢 Magoo。该代码会跳过已经压缩的文件,但也会跳过具有双扩展名的文件(可能有这样的文件)。此外,我猜根据我提出的语法,压缩文件不再在源文件夹上创建,而是出现在我放置批处理文件的位置。回答您的问题:因为它会再次压缩没有更改的大文件(如果有更改,它将变为“v2”左右),这是不可取的。
    • 让我建议引用 if not exist "%%~nI.zip" if not exist "%%~nI.7z"...
    • @aschipfl TY 但我没有让它工作。无论如何,我需要处理文件名,然后确保压缩发生在源文件夹上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多