如何将具有相对组件的路径转换为Windows批处理文件中的绝对路径?

时间:2015-05-12 10:24:54

标签: batch-file

给出具有相对分量的路径:

c:\foo\..\temp\file.txt

我想“删除/扩展”相对部分,

c:\temp\file.txt

如何将具有相对组件的路径转换为Windows批处理文件中的绝对路径?

3 个答案:

答案 0 :(得分:1)

这很容易。如果您正在使用文件夹,请使用:

@echo off
set rel=c:\foo\..\temp
set abs=
pushd %rel%
set abs=%CD%
popd
echo relative path is %rel%
echo absolute path is %abs%

我们来看看代码。无论您身在何处,pushd %rel%都会保存您当前的位置,并将目录更改为%relpath%,即c:\foo\..\temp。更改目录%CD%后,将包含已解析的路径C:\temp。此路径将存储在变量%abs%中。除此步骤之外,您执行popd,它将带您返回与pushd一起存储的目录。所以最后你通过跳转到它来解决相对路径,将其保存在%abs%中并跳回到当前目录。

编辑:如果您正在处理文件,这将有效:

@ECHO OFF
SET rel=c:\foo\..\temp\file.txt
FOR /f %%i IN ("%rel%") DO (
    SET abs=%%~di%%~pi%%~ni%%~xi
)
ECHO %abs%

答案 1 :(得分:1)

如果它是一个参数,您可以使用~f展开它,例如%~f1

如果不是,您可以将其作为子程序的参数:

call :absPath %RELPATH%
exit /b

:absPath
echo Absolute path: %~f1

答案 2 :(得分:1)

@echo off
setlocal enableextensions disabledelayedexpansion
set "relative=c:\foo\..\temp\file.txt"

for %%a in ("%relative%") do set "absolute=%%~fa"

echo %relative% = %absolute%

使用fortechnet documentation)可替换参数中的修饰符来获取指定元素的完整路径(有关完整列表,请参阅for /?

%~I        Expands %I which removes any surrounding quotation marks ("").
%~fI       Expands %I to a fully qualified path name.
%~dI       Expands %I to a drive letter only.
%~pI       Expands %I to a path only.
%~nI       Expands %I to a file name only.
%~xI       Expands %I to a file extension only.
%~sI       Expands path to contain short names only.
%~aI       Expands %I to the file attributes of file.
%~tI       Expands %I to the date and time of file.
%~zI       Expands %I to the size of file.
%~$PATH:I  Searches the directories listed in the PATH environment variable and
           expands %I to the fully qualified name of the first one found. If
           the environment variable name is not defined or the file is not
           found by the search, this modifier expands to the empty string.

文件或文件夹的工作方式相同,如果它们存在与否则相同。