【问题标题】:How to replace a file at destination with another file at source location using nested for loop in cmd如何使用cmd中的嵌套for循环将目标文件替换为源位置的另一个文件
【发布时间】:2019-11-11 16:20:22
【问题描述】:

在一个文件夹下,例如sourcefiles,我有三个.aar文件:

D:\test\sourcefiles\netQ-1.aar
D:\test\sourcefiles\netQ-2.aar
D:\test\sourcefiles\netQ-3.aar

我想替换三个不同位置的.aar 文件,

D:\fido\netQ-1\netQ-1.aar
D:\fido\netQ-2\netQ-2.aar
D:\fido\netQ-3\netQ-3.aar

sourcefiles 位置的文件,但前提是目标位置的文件名称与其名称匹配,即

D:\fido\netQ-1\netQ-1.aar 替换为D:\test\sourcefiles\netQ-1.aar
D:\fido\netQ-2\netQ-2.aarD:\test\sourcefiles\netQ-2.aar
D:\fido\netQ-3\netQ-2.aarD:\test\sourcefiles\netQ-3.aar

为此,我尝试使用嵌套的 for 循环 命令:

for /d %a in ('dir /b  D:\test\sourcefiles\*.aar') do FOR /F "usebackq" %b in (`DIR /s /b  D:\fido\\.aar`) do (if /i "%%~xa" equ "%%~xb" (replace the files ))

在这个If 条件下,我尝试匹配文件名,然后执行替换操作。实现此目的的正确命令是什么?

【问题讨论】:

    标签: windows for-loop batch-file if-statement cmd


    【解决方案1】:

    鉴于您提供的确切输入示例:

    来自cmd

    @for %i in ("D:\test\sourcefiles\*.aar") do if exist "D:\fido\%~ni\%~nxi" copy "%~i" "D:\fido\%~ni\%~nxi" /Y
    

    从批处理文件中:

    @echo off
    for %%i in ("D:\test\sourcefiles\*.aar") do if exist "D:\fido\%%~ni\%%~nxi" copy "%%~i" "D:\fido\%%~ni\%%~nxi" /Y
    

    仅当目标文件夹与示例中显示的不带扩展名的文件名完全相同时才有效。

    注意在这两种情况下,只有当您对 echo 的结果感到满意时才删除 echo。 Echo 只是一种安全措施。

    【讨论】:

    • 它不起作用。我看到以下输出命令,例如 if exists "D:\fido\netQ-1\D:\test\sourcefiles\netQ-1.aar" copy "D:\test\sourcefiles\netQ-1.aar" "D: \fido\netQ-1\D:\test\sourcefiles\netQ-1.aar" /Y 但是当我检查 dest5ination 文件夹时,我没有看到目标的 .aar 文件被修改。它仍然没有被替换。
    • 不管怎样,我编辑了答案为你删除了echo,你现在可以试试。
    • 现在我收到错误:文件名、目录名或卷标语法不正确。已复制 0 个文件。
    • 谢谢你现在可以使用了。需要对您的解决方案进行细微更改,而不是 if exist "D:\fido\%~ni\%~nxi" copy "%~i" "D:\fido\%~ni\%~i" /Y 它应该是 if exist "D:\fido\%~ni\%~nxi" copy "%~i" "D:\fido\%~ni\%~ni.aar" /Y
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 2021-08-09
    相关资源
    最近更新 更多