Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalize file path in batch

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?

like image 974
pschill Avatar asked Feb 13 '18 10:02

pschill


People also ask

How do I create an absolute path in a batch file?

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.

What does \\ mean in Windows 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 \\ .

How do you handle spaces in a batch file?

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" .

How do I create an absolute path in Windows?

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.


1 Answers

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 /?

like image 152
Stephan Avatar answered Sep 28 '22 01:09

Stephan