3

I'm doing some BATCH scripting looping through files to copy. But I came to a problem where I need the path relative to the current .bat execution folder (%cd%)

So if I have files like this:

  • c:\games\batchTest\test.bat
  • c:\games\batchTest\subFolder1\test1.txt

How can I get just "subFolder1\test1.txt" so I can copy the file with the sub folder?

My current code:

for /r %%a in (*) do ( echo "%%a" ) 
7
  • in cmd.exe, type For /? Read the information regarding expanding path related variables during For loops. Commented Jan 8, 2020 at 14:39
  • 1
    Copying should work the same with a full path as it would a relative one. Perhaps you should explain your task with more detail. Commented Jan 8, 2020 at 15:34
  • I'm trying to copy all files from folderA to folderB, keeping the sub directories Commented Jan 8, 2020 at 16:54
  • Also I need to filter out some files Commented Jan 8, 2020 at 17:10
  • 1
    You may not need a for loop or relative paths. I you open up a Command Prompt window and enter both xcopy /? and robocooy /?, read through their usage information and choose whichever of them you wish, it may be sufficient for your needs. Robocopy is the newer, and was built to supercede xcopy, so I'd recommend that if you're unsure. Commented Jan 8, 2020 at 17:43

2 Answers 2

1

You can try this:

@Echo Off Setlocal enabledelayedexpansion For /r %%a In (*) Do ( Set p="%%a" Echo !p:%__CD__%=! ) 
Sign up to request clarification or add additional context in comments.

Comments

1

The for /R loop always returns absolute paths, even if the (optional) given root directory behind /R is relative.

A possible way to get relative paths is to (mis-)use the xcopy command together with its /L option that prevents anything to be copied:

xcopy /L /S /I ".\*.*" "%TEMP%" 

To remove the summary line # File(s) apply a filter using find using a pipe:

xcopy /L /S /I ".\*.*" "%TEMP%" | find ".\" 

To process the returned items use a for /F loop:

for /F "eol=| delims=" %%F in (' xcopy /L /S /I ".\*.*" "%TEMP%" ^| find ".\" ') do ( echo Processing file "%%F"... ) 

If you just want to copy files including the sub-directory structure you do not even need the above stuff with for loops, you can simply use xcopy:

xcopy /S /I "D:\Source\*.*" "D:\Destination" 

or robocopy:

robocopy /S "D:\Source" "D:\Destination" "*.*" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.