2

我想在 Windows 7 中实现一个批处理脚本,它遍历文件夹中的所有文件并剪切文件夹前缀,例如 Folder = "C:\A\B\" 和 file = "C:\A\B\C \DE" 应该输出 "C\DE"。我当前的代码如下所示:

setlocal ENABLEDELAYEDEXPANSION
SET DIRECTORY=C:\DEV\SVN\QA\
for /R %DIRECTORY% %%f in (*.*) do (
REM GET RELATIVE PATH
echo File=%%f
echo Path=%TARGET_PATH_FOR_SOURCE%
set result=%f:!TARGET_PATH_FOR_SOURCE!=%

echo Result=!result!
)

我得到以下结果:

File=C:\DEV\SVN\QA\1.0\A\B\C.txt
Path=C:\DEV\SVN\QA\1.0
Result=C:\DEV\SVN\QA\1.0=    <<< Expected result: "A\B\C.txt" 

我在这里找到了这个并在循环中尝试了这个但没有成功。你能帮我吗?

谢谢!

4

2 回答 2

4

这应该有效。

有必要将 FOR 循环参数复制到变量中,因为替换操作仅适用于变量。

@echo off
setlocal EnableDelayedExpansion
SET DIRECTORY==C:\DEV\SVN\QA
set TARGET_PATH_FOR_SOURCE==C:\DEV\SVN\QA\1.0
echo Path=%TARGET_PATH_FOR_SOURCE%
for /R %DIRECTORY% %%x in (*.*) do (
    REM GET RELATIVE PATH
    set "file=%%x"
    set result=!file:%TARGET_PATH_FOR_SOURCE%=!
    echo Result=!result!
)
于 2013-11-13T12:35:24.440 回答
2

提到“jeb”的答案:我为这个工作而头痛了好几个小时。显然这比预期的要容易。这:

SET DIRECTORY==C:\DEV\SVN\QA
set TARGET_PATH_FOR_SOURCE==C:\DEV\SVN\QA\1.0

必须不带“==”:

set DIRECTORY=C:\DEV\SVN\QA
set TARGET_PATH_FOR_SOURCE=C:\DEV\SVN\QA\1.0

编辑:嗯,事实证明我必须做更多。另外改变这个:

set result=!file:%TARGET_PATH_FOR_SOURCE%=!

对此,应该没问题:

call set result=%%file:!TARGET_PATH_FOR_SOURCE!=%%
于 2014-05-02T15:37:27.407 回答