在Windows批处理脚本中,有没有办法从包含文件名和/或相对路径的值返回绝对路径?
给定的:
"..\"
"..\somefile.txt"
我需要相对于批处理文件的绝对路径。
示例:
%1
派生的批处理文件"C:\Foo\somefile.txt”
发布于 2009-10-30 03:25:34
在批处理文件中,与标准C程序一样,参数0包含当前正在执行的脚本的路径。您可以使用%~dp0
来仅获取第0个参数(即当前脚本)的路径部分-此路径始终是完全限定的路径。
您也可以使用%~f1
获得第一个参数的完全限定路径,但这将根据当前工作目录提供一个路径,这显然不是您想要的。
就我个人而言,我经常在批处理文件中使用%~dp0%~1
习惯用法,它解释相对于正在执行的批处理的路径的第一个参数。但它确实有一个缺点:如果第一个参数是完全限定的,那么它就会不幸地失败。
如果需要同时支持相对路径和绝对路径,可以使用Frédéric Ménez's solution:临时更改当前工作目录。
下面是一个示例,它将演示这些技术:
@echo off
echo %%~dp0 is "%~dp0"
echo %%0 is "%0"
echo %%~dpnx0 is "%~dpnx0"
echo %%~f1 is "%~f1"
echo %%~dp0%%~1 is "%~dp0%~1"
rem Temporarily change the current working directory, to retrieve a full path
rem to the first parameter
pushd .
cd %~dp0
echo batch-relative %%~f1 is "%~f1"
popd
如果您将其另存为c:\temp\example.bat,并从c:\Users\Public运行它为
c:\Users\Public>\temp\example.bat ..\windows
...您将看到以下输出:
%~dp0 is "C:\temp\"
%0 is "\temp\example.bat"
%~dpnx0 is "C:\temp\example.bat"
%~f1 is "C:\Users\windows"
%~dp0%~1 is "C:\temp\..\windows"
batch-relative %~f1 is "C:\Windows"
有关批处理参数上允许的修饰符集合的文档可在以下位置找到:https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/call
发布于 2010-12-20 18:26:11
今天早上我遇到了一个类似的需求:如何在Windows命令脚本中将相对路径转换为绝对路径。
下面的代码起到了作用:
@echo off
set REL_PATH=..\..\
set ABS_PATH=
rem // Save current directory and change to target directory
pushd %REL_PATH%
rem // Save value of CD variable (current directory)
set ABS_PATH=%CD%
rem // Restore original directory
popd
echo Relative path: %REL_PATH%
echo Maps to path: %ABS_PATH%
发布于 2015-10-29 10:18:51
这些答案中的大多数似乎都是对复杂和超级错误的疯狂,这里是我的答案--它适用于任何环境变量,没有%CD%
、PUSHD
/POPD
或for /f
胡说八道--只有普通的老式批处理函数。--目录和文件甚至不需要存在。
CALL :NORMALIZEPATH "..\..\..\foo\bar.txt"
SET BLAH=%RETVAL%
ECHO "%BLAH%"
:: ========== FUNCTIONS ==========
EXIT /B
:NORMALIZEPATH
SET RETVAL=%~f1
EXIT /B
https://stackoverflow.com/questions/1645843
复制相似问题