Reputation: 129
Can you get relative file path of the file regarding the execution path in batch script?
What I mean is this:
running batch script in:
c:\batchTest\test.bat
and there's a file at:
c:\batchTest\sub\example.txt
how do you in test.bat get the "sub" extracted? because that's relative folder regarding the batch script
I am currently running this batch script but need the relative path for program output (returns full path I need only relative path):
for /r %%i in (*.txt) do echo %%~dpi
Upvotes: 0
Views: 677
Reputation: 38579
Save each string result to a variable, enable delayed expansion, then expand the variable to replace the batch file path with .\
.
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
For /R "%~p0" %%I In ("*.txt") Do (
Set "pth=%%~pI"
SetLocal EnableDelayedExpansion
Set "rel=!pth:%~p0=.\!"
Echo !rel:~,-1!
EndLocal
)
Pause
If you want trailing backslahes, then change !rel:~,-1!
to !rel!
If the command is processing files one by one, then I'd suggest you would be wanting the relative file path, not its relative parent directory. If so then this should work for you:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
For /R "%~p0" %%I In ("*.txt") Do (
Set "pth=%%~pnxI"
SetLocal EnableDelayedExpansion
Echo !pth:%~p0=.\!
EndLocal
)
Pause
In this case, you'd replace Echo !pth:%~p0=.\!
with your command, (using !pth:%~p0=.\!
as your relative path).
Upvotes: 2