关于windows:将绝对路径转换为批处理文件中的相对路径

Convert absolute path to relative path in batch file

是否可以将绝对路径转换为批处理文件中的相对路径?(与此相反)。显然,您需要两个输入:要转换的绝对路径,以及要将其相对化的绝对引用路径。

如:

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


1
2
3
4
5
6
@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%


如果您想从字符串的开头删除%cd%,这是另一个有效的方法。虽然速度很慢,但是如果情况允许,可以减少循环的数量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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