Convert absolute path to relative path in batch file

风流意气都作罢 提交于 2019-11-30 14:08:38
@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%

Here is another method that works if your want to remove the %cd% from the start of a string. It is slow but you could lower the number of loops if you situation allowed it.

call :removeCommonAtStart outvar C:\Users\Public\Documents\ASUSAccess

:removeCommonAtStart
:: Description: loops through two strings and sets new variable representing unique data
:: Required parameters:
:: name - name of the variable to be returned
:: test - string to have common data removed from start
:: Optional parameters:
:: remove - string if not defined then use %cd% as string.
:: Required functions:
:: removelet
set name=%~1
set test=%~2
set remove=%~3
if not defined remove set remove=%cd%
set endmatch=
FOR /L %%l IN (0,1,150) DO if not defined notequal call :removelet
goto :eof

:removelet
:: Description: called by removeCommonAtStart to remove one letter from the start of two string variables
:: Required preset variables:
:: test
:: remove
:: name
set test=%test:~1%
set %name%=%test:~1%
set remove=%remove:~1%
if "%test:~0,1%" neq "%remove:~0,1%" set notequal=on&exit /b
goto :eof
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!