2

I want to implement a batch script in Windows 7 that iterates over all files in a folder and it cuts the folder prefix, e.g. Folder = "C:\A\B\" and the file = "C:\A\B\C\D.E" should output "C\D.E". My current code looks like this:

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!
)

I get the following 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" 

I found this here and tried this in the loop without success. Can you help me please?

Thank you!

Community
  • 1
  • 1
user2722077
  • 462
  • 1
  • 8
  • 21

2 Answers2

4

This should work.

It's necessary to copy the FOR loop parameter to a variable, as the replace operations works only with variables.

@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!
)
jeb
  • 78,592
  • 17
  • 171
  • 225
2

referring to answer of "jeb": i had a headache for hours getting this to work. obviously it was easier than expected. this:

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

must be written without "==":

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

EDIT: Well, It turns out that I had to do even more. Additionally change this:

set result=!file:%TARGET_PATH_FOR_SOURCE%=!

to this, then it should be fine:

call set result=%%file:!TARGET_PATH_FOR_SOURCE!=%%
SourceSeeker
  • 121
  • 7