问题描述
有没有在Windows批处理脚本的方式从一个包含文件名和/或相对路径返回一个值的绝对路径?
Is there a way in a Windows batch script to return an absolute path from a value containing a filename and/or relative path?
考虑:
"..\"
"..\somefile.txt"
我需要绝对相对于该批处理文件的路径。
I need the absolute path relative to the batch file.
示例:
- somefile.txt位于C:\\富\\
- test.bat的位于C:\\富\\栏。
- 用户在打开一个命令窗口C:\\富,并呼吁
酒吧\\ test.bat的.. \\ somefile.txt
- 在批处理文件C:\\富\\ somefile.txt将从
%1
导出
- "somefile.txt" is located in "C:\Foo\"
- "test.bat" is located in "C:\Foo\Bar".
- User opens a command window in "C:\Foo" and calls
Bar\test.bat ..\somefile.txt
- In the batch file "C:\Foo\somefile.txt" would be derived from
%1
推荐答案
在批处理文件,如标准的C程序,参数0包含路径到当前执行脚本。您可以使用%〜DP0
只得到第0参数的路径部分(这是当前脚本) - 这条道路始终是一个完全合格的路径
In batch files, as in standard C programs, argument 0 contains the path to the currently executing script. You can use %~dp0
to get only the path portion of the 0th argument (which is the current script) - this path is always a fully qualified path.
您还可以使用让你的第一个参数的完全合格的路径%〜F1
,但根据当前工作目录,这显然不是这给路径你要什么。
You can also get the fully qualified path of your first argument by using %~f1
, but this gives a path according to the current working directory, which is obviously not what you want.
就个人而言,我经常使用%〜DP0%〜1
成语在我的批处理文件,其中除$ P $首先相对于执行路径参数PT批量。它有一个缺点,虽然:如果第一个参数是完全合格的IT悲惨的失败了。
Personally, I often use the %~dp0%~1
idiom in my batch file, which interpret the first argument relative to the path of the executing batch. It does have a shortcoming though: it miserably fails if the first argument is fully-qualified.
如果您需要同时支持相对的和的绝对路径,你可以使用Frédéric梅内的解决方案:暂时改变当前的工作目录。
If you need to support both relative and absolute paths, you can make use of Frédéric Ménez's solution: temporarily change the current working directory.
下面是将演示每种技术的例子:
Here's an example that'll demonstrate each of these techniques:
@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运行它:\\用户\\公用为
If you save this as c:\temp\example.bat and the run it from c:\Users\Public as
C:\\用户\\公用> \\ TEMP \\ example.bat .. \\ WINDOWS
c:\Users\Public>\temp\example.bat ..\windows
...你会看到下面的输出:
...you'll observe the following output:
%~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"
这篇关于解析从相对路径和/或文件名绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!