从相对路径和/或文件名解析绝对路径 [英] Resolve absolute path from relative path and/or file name
问题描述
在 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:Foo"
- "test.bat" 位于 "C:FooBar".
- 用户在C:Foo"中打开一个命令窗口并调用
Bar est.bat ..somefile.txt
- 在批处理文件中C:Foosomefile.txt"将从
%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
习惯用法,它解释相对于执行批处理的路径的第一个参数.但它确实有一个缺点:如果第一个参数是完全限定的,它就会失败.
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 Ménez 的解决方案:临时更改当前工作目录.
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: empexample.bat 并从 c:UsersPublic as 运行它
If you save this as c: empexample.bat and the run it from c:UsersPublic as
c:UsersPublic> empexample.bat ..windows
c:UsersPublic> empexample.bat ..windows
...您将观察到以下输出:
...you'll observe the following output:
%~dp0 is "C: emp"
%0 is " empexample.bat"
%~dpnx0 is "C: empexample.bat"
%~f1 is "C:Userswindows"
%~dp0%~1 is "C: emp..windows"
batch-relative %~f1 is "C:Windows"
可以在此处找到批处理参数所允许的一组修饰符的文档:https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/call
the documentation for the set of modifiers allowed on a batch argument can be found here: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/call
这篇关于从相对路径和/或文件名解析绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!