7

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?

pschill
  • 5,055
  • 1
  • 21
  • 42
  • https://stackoverflow.com/a/33404867/2029097 – Marian Feb 13 '18 at 10:09
  • That's not what I'd call an absolute path, I'd call it a relative path! I suppose you should clarify whether or not the file path given exists on the end users system. _(If it doesn't, i.e. is just a string, the answer may be completely different!)_ – Compo Feb 13 '18 at 10:21
  • @Compo I thought the difference between a relative and an absolute path is the following: Relative paths start from the working directory, absolute paths start from the file system root. My path is absolute since it starts with `C:`. I think what you mean is called _normalized path_. – pschill Feb 13 '18 at 10:26
  • Surely all you need to do is in the example you've given is remove the "\project\.." from the path? – SPlatten Feb 13 '18 at 10:28
  • @SPlatten The paths come from the command line arguments, so I cant just replace the string. I edited the question to clarify that. – pschill Feb 13 '18 at 10:34
  • 1
    I recommend using `%~1` and `%~2` to remove eventually surrounding quotes (quotes are needed to give a path or file name with spaces as *one* argument). – Stephan Feb 13 '18 at 10:46

1 Answers1

14

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

Stephan
  • 53,940
  • 10
  • 58
  • 91
  • I edited the question and added that the path is built from command line arguments. – pschill Feb 13 '18 at 10:37
  • Thanks, this works for the example values from my question. Is there a similar method for relative paths? For example, the path `data\..\..\other\abc.txt` should be transformed to `..\other\abc.txt`. – pschill Feb 13 '18 at 10:43
  • no, this always generates, what you called a "normalized path" – Stephan Feb 13 '18 at 10:45