Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file relative path to current dir

Tags:

batch-file

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"

)
like image 807
Coder547 Avatar asked Feb 16 '26 17:02

Coder547


2 Answers

You can try this:

@Echo Off
Setlocal enabledelayedexpansion 
For /r %%a In (*) Do (
  Set p="%%a"
  Echo !p:%__CD__%=!
)
like image 96
programmer365 Avatar answered Feb 18 '26 07:02

programmer365


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" "*.*"
like image 21
aschipfl Avatar answered Feb 18 '26 06:02

aschipfl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!