Is there a way to resolve the ..
from an absolute file path in batch? For example, the following batch script should output C:\Users\xyz\other\abc.txt
:
REM Project dir is an absolute path, for example, C:\Users\xyz\project\
SET projectDir=%~1
REM Target file is a path relative to the project dir, for example, ..\other\abc.txt
SET target=%~2
REM Concatenate paths. This becomes C:\Users\xyz\project\..\other\abc.txt
SET absoluteTarget=%projectDir%%target%
SET absoluteTargetClean=...
echo %absoluteTargetClean%
The absoluteTarget
variable refers to an existing file.
I need the same for a directory instead of the file. Can you use the same way to achieve that?
In batch files, as in standard C programs, argument 0 contains the path to the currently executing script. You can use %~dp0 to get only the path portion of the 0th argument (which is the current script) - this path is always a fully qualified path.
Universal naming convention (UNC) paths, which are used to access network resources, have the following format: A server or host name, which is prefaced by \\ .
When you send arguments, those with poison or space characters need to be doublequoted. Inside your batch file, if you no longer need the surrounding doublequotes, you'd remove them by using %~5 instead of %5 . Additionally the recommended syntax for the set command is Set "VariableName=VariableValue" .
You can determine the absolute path of any file in Windows by right-clicking a file and then clicking Properties. In the file properties first look at the "Location:" which is the path to the file.
I wonder, how anyone ever could come up with a path like C:\Users\xyz\project\..\other\abc.txt
, but here we go:
SET "absPath=C:\Users\xyz\project\..\other\abc.txt"
for %%i in ("%absPath%") do SET "absPathClean=%%~fi"
echo %absPathClean%
works for both files and folders.
For more information, consult for /?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With