Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Batch file 如何将包含相对组件的路径转换为windows批处理文件中的绝对路径?_Batch File - Fatal编程技术网

Batch file 如何将包含相对组件的路径转换为windows批处理文件中的绝对路径?

Batch file 如何将包含相对组件的路径转换为windows批处理文件中的绝对路径?,batch-file,Batch File,给定具有相关组件的路径: c:\foo\..\temp\file.txt 我想“删除/扩展”相关部分 c:\temp\file.txt 如何将包含相对组件的路径转换为windows批处理文件中的绝对路径?这很简单。如果您正在使用文件夹,请使用以下选项: @echo off set rel=c:\foo\..\temp set abs= pushd %rel% set abs=%CD% popd echo relative path is %rel% echo absolute path is

给定具有相关组件的路径:

c:\foo\..\temp\file.txt
我想“删除/扩展”相关部分

c:\temp\file.txt

如何将包含相对组件的路径转换为windows批处理文件中的绝对路径?

这很简单。如果您正在使用文件夹,请使用以下选项:

@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%

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

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

call :absPath %RELPATH%
exit /b

:absPath
echo Absolute path: %~f1
@echo关闭
setlocal enableextensions disabledelayedexpansion
设置“relative=c:\foo\..\temp\file.txt”
对于(“%relative%”)中的%%a,请设置“绝对=%%~fa”
回显%相对%=%绝对%
使用
中的修饰符(适用于
()可替换参数)获取指向所示元素的完整路径(请参见
以获取/?
以获取完整列表)


将对文件或文件夹起同样的作用,如果它们存在或不存在,都是一样的。

谢谢。我使用的是文件名而不是目录。我更新了我的问题,使之更清楚。我不确定您的方法是否也适用于文件名,但最好知道是否处理目录。@MichaWiedenmann我已经编辑了我的帖子并添加了文件处理。
%~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.