Search code examples
windowsbatch-filerelative-pathabsolute-path

Convert absolute path to relative path in batch file


Is it possible to convert an absolute path to a relative path in a batch file? (the opposite of this). Obviously you would need two inputs: the absolute path to convert, and an absolute reference path that you want it to be relativised to.

eg:

Path to convert: c:\documents\mynicefiles\afile.txt
Reference path:  c:\documents
Result:          mynicefiles\afile.txt

Solution

  • @echo off
    setlocal EnableDelayedExpansion
    set Path_to_convert=c:\documents\mynicefiles\afile.txt
    set Reference_path=c:\documents
    set Result=!Path_to_convert:*%Reference_path%\=!
    echo Result: %Result%