windows 从相对路径和/或文件名解析绝对路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1645843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:52:16  来源:igfitidea点击:

Resolve absolute path from relative path and/or file name

windowsbatch-filerelative-pathabsolute-path

提问by Nathan Taylor

Is there a way in a Windows batch script to return an absolute path from a value containing a filename and/or relative path?

Windows 批处理脚本中有没有办法从包含文件名和/或相对路径的值返回绝对路径?

Given:

鉴于:

"..\"
"..\somefile.txt"

I need the absolute path relative to the batch file.

我需要相对于批处理文件的绝对路径。

Example:

例子:

  • "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
  • “somefile.txt”位于“C:\Foo\”
  • “test.bat”位于“C:\Foo\Bar”。
  • 用户在“C:\Foo”中打开一个命令窗口并调用 Bar\test.bat ..\somefile.txt
  • 在批处理文件中“C:\Foo\somefile.txt”将来自 %1

回答by Adrien Plisson

In batch files, as in standard C programs, argument 0 contains the path to the currently executing script. You can use %~dp0to get only the path portion of the 0th argument (which is the current script) - this path is always a fully qualified path.

在批处理文件中,就像在标准 C 程序中一样,参数 0 包含当前正在执行的脚本的路径。您可以使用%~dp0仅获取第 0 个参数(即当前脚本)的路径部分 - 此路径始终是完全限定的路径。

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.

您还可以使用 获取第一个参数的完全限定路径%~f1,但这会根据当前工作目录给出路径,这显然不是您想要的。

Personally, I often use the %~dp0%~1idiom 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.

就我个人而言,我经常%~dp0%~1在我的批处理文件中使用这个习惯用法,它解释相对于执行批处理的路径的第一个参数。但是它确实有一个缺点:如果第一个参数是完全限定的,它就会失败。

If you need to support both relative andabsolute paths, you can make use of Frédéric Ménez's solution: temporarily change the current working directory.

如果您需要同时支持相对路径绝对路径,您可以使用Frédéric Ménez 的解决方案:临时更改当前工作目录。

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

If you save this as c:\temp\example.bat and the run it from c:\Users\Public as

如果你将它保存为 c:\temp\example.bat 并从 c:\Users\Public 运行它作为

c:\Users\Public>\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"

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

可以在此处找到批处理参数允许的一组修饰符的文档:https: //docs.microsoft.com/en-us/windows-server/administration/windows-commands/call

回答by Frédéric Ménez

I came across a similar need this morning: how to convert a relative path into an absolute path inside a Windows command script.

今天早上我遇到了类似的需求:如何在 Windows 命令脚本中将相对路径转换为绝对路径。

The following did the trick:

以下是诀窍:

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

回答by BrainSlugs83

Most of these answers seem crazy over complicated and super buggy, here's mine -- it works on any environment variable, no %CD%or PUSHD/POPD, or for /fnonsense -- just plain old batch functions. -- The directory & file don't even have to exist.

这些答案中的大多数似乎都因复杂和超级错误而疯狂,这是我的 - 它适用于任何环境变量,没有%CD%PUSHD/POPDfor /f废话 - 只是简单的旧批处理函数。-- 目录和文件甚至不必存在。

CALL :NORMALIZEPATH "..\..\..\foo\bar.txt"
SET BLAH=%RETVAL%

ECHO "%BLAH%"

:: ========== FUNCTIONS ==========
EXIT /B

:NORMALIZEPATH
  SET RETVAL=%~dpfn1
  EXIT /B

回答by Peter Ritchie

Without having to have another batch file to pass arguments to (and use the argument operators), you can use FOR /F:

不必有另一个批处理文件来传递参数(并使用参数运算符),您可以使用FOR /F

FOR /F %%i IN ("..\relativePath") DO echo absolute path: %%~fi

where the iin %%~fiis the variable defined at /F %%i. eg. if you changed that to /F %%athen the last part would be %%~fa.

其中iin%%~fi是在 处定义的变量/F %%i。例如。如果您将其更改为,/F %%a那么最后一部分将是%%~fa.

To do the same thing right at the command prompt (and not in a batch file) replace %%with %...

要在命令提示符下(而不是在批处理文件中)执行相同的操作,请替换%%%...

回答by Kurt Pfeifle

This is to help fill in the gaps in Adrien Plisson's answer (which should be upvoted as soon as he edits it ;-):

这是为了帮助填补 Adrien Plisson 的答案中的空白(一旦他编辑它就应该被赞成;-):

you can also get the fully qualified path of your first argument by using %~f1, but this gives a path according to the current path, which is obviously not what you want.

unfortunately, i don't know how to mix the 2 together...

您还可以使用 %~f1 获取第一个参数的完全限定路径,但这会根据当前路径给出路径,这显然不是您想要的。

不幸的是,我不知道如何将两者混合在一起......

One can handle %0and %1likewise:

一个人可以处理%0%1同样:

  • %~dpnx0for fully qualified drive+path+name+extension of the batchfile itself,
    %~f0also suffices;
  • %~dpnx1for fully qualified drive+path+name+extension of its first argument [if that's a filename at all],
    %~f1also suffices;
  • %~dpnx0对于完全限定的驱动器+路径+名称+批处理文件本身的扩展名,
    %~f0也足够了;
  • %~dpnx1对于完全限定的驱动器+路径+名称+其第一个参数的扩展名[如果那是一个文件名],
    %~f1也足够了;

%~f1will work independent of how you did specify your first argument: with relative paths or with absolute paths (if you don't specify the file's extension when naming %1, it will not be added, even if you use %~dpnx1-- however.

%~f1将独立于您指定第一个参数的方式工作:使用相对路径或使用绝对路径(如果您在命名时未指定文件的扩展名%1,则不会添加它,即使您使用%~dpnx1-- 但是。

But how on earth would you name a file on a different driveanyway if you wouldn't give that full path info on the commandline in the first place?

但是,如果您不首先在命令行上提供完整路径信息,您到底如何命名不同驱动器上的文件?

However, %~p0, %~n0, %~nx0and %~x0may come in handy, should you be interested in path (without driveletter), filename (without extension), full filename with extension or filename's extension only. But note, while %~p1and %~n1will work to find out the path or name of the first argument, %~nx1and %~x1will not add+show the extension, unless you used it on the commandline already.

但是,如果您对路径(不带驱动器号)、文件名(不带扩展名)、带扩展名的完整文件名或仅文件名的扩展名感兴趣%~p0%~n0,%~nx0%~x0可能会派上用场。但请注意,while%~p1%~n1将找出第一个参数的路径或名称,%~nx1并且%~x1不会添加+显示扩展名,除非您已经在命令行上使用它。

回答by Axel Heider

You can also use batch functions for this:

您还可以为此使用批处理函数:

@echo off
setlocal 

goto MAIN
::-----------------------------------------------
:: "%~f2" get abs path of %~2. 
::"%~fs2" get abs path with short names of %~2.
:setAbsPath
  setlocal
  set __absPath=%~f2
  endlocal && set %1=%__absPath%
  goto :eof
::-----------------------------------------------

:MAIN
call :setAbsPath ABS_PATH ..\
echo %ABS_PATH%

endlocal

回答by Axel Heider

Small improvement to BrainSlugs83's excellent solution. Generalized to allow naming the output environment variable in the call.

BrainSlugs83 的优秀解决方案的小改进。概括为允许在调用中命名输出环境变量。

@echo off
setlocal EnableDelayedExpansion

rem Example input value.
set RelativePath=doc\build

rem Resolve path.
call :ResolvePath AbsolutePath %RelativePath%

rem Output result.
echo %AbsolutePath%

rem End.
exit /b

rem === Functions ===

rem Resolve path to absolute.
rem Param 1: Name of output variable.
rem Param 2: Path to resolve.
rem Return: Resolved absolute path.
:ResolvePath
    set %1=%~dpfn2
    exit /b

If run from C:\projectoutput is:

如果从C:\project输出运行是:

C:\project\doc\build

回答by dayneo

I have not seen many solutions to this problem. Some solutions make use of directory traversal using CD and others make use of batch functions. My personal preference has been for batch functions and in particular, the MakeAbsolutefunction as provided by DosTips.

我还没有看到这个问题的很多解决方案。一些解决方案使用 CD 进行目录遍历,而其他解决方案使用批处理功能。我个人更喜欢批处理功能,特别是DosTips提供的MakeAbsolute功能。

The function has some real benefits, primarily that it does not change your current working directory and secondly that the paths being evaluated don't even have to exist. You can find some helpful tips on how to use the function heretoo.

这个函数有一些真正的好处,主要是它不会改变你当前的工作目录,其次被评估的路径甚至不必存在。您也可以在此处找到有关如何使用该功能的一些有用提示。

Here is an example script and its outputs:

这是一个示例脚本及其输出:

@echo off

set scriptpath=%~dp0
set siblingfile=sibling.bat
set siblingfolder=sibling\
set fnwsfolder=folder name with spaces\
set descendantfolder=sibling\descendant\
set ancestorfolder=..\..\
set cousinfolder=..\uncle\cousin

call:MakeAbsolute siblingfile      "%scriptpath%"
call:MakeAbsolute siblingfolder    "%scriptpath%"
call:MakeAbsolute fnwsfolder       "%scriptpath%"
call:MakeAbsolute descendantfolder "%scriptpath%"
call:MakeAbsolute ancestorfolder   "%scriptpath%"
call:MakeAbsolute cousinfolder     "%scriptpath%"

echo scriptpath:       %scriptpath%
echo siblingfile:      %siblingfile%
echo siblingfolder:    %siblingfolder%
echo fnwsfolder:       %fnwsfolder%
echo descendantfolder: %descendantfolder%
echo ancestorfolder:   %ancestorfolder%
echo cousinfolder:     %cousinfolder%
GOTO:EOF

::----------------------------------------------------------------------------------
:: Function declarations
:: Handy to read http://www.dostips.com/DtTutoFunctions.php for how dos functions
:: work.
::----------------------------------------------------------------------------------
:MakeAbsolute file base -- makes a file name absolute considering a base path
::                      -- file [in,out] - variable with file name to be converted, or file name itself for result in stdout
::                      -- base [in,opt] - base path, leave blank for current directory
:$created 20060101 :$changed 20080219 :$categories Path
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set "src=%~1"
if defined %1 set "src=!%~1!"
set "bas=%~2"
if not defined bas set "bas=%cd%"
for /f "tokens=*" %%a in ("%bas%.\%src%") do set "src=%%~fa"
( ENDLOCAL & REM RETURN VALUES
    IF defined %1 (SET %~1=%src%) ELSE ECHO.%src%
)
EXIT /b

And the output:

和输出:

C:\Users\dayneo\Documents>myscript
scriptpath:       C:\Users\dayneo\Documents\
siblingfile:      C:\Users\dayneo\Documents\sibling.bat
siblingfolder:    C:\Users\dayneo\Documents\sibling\
fnwsfolder:       C:\Users\dayneo\Documents\folder name with spaces\
descendantfolder: C:\Users\dayneo\Documents\sibling\descendant\
ancestorfolder:   C:\Users\
cousinfolder:     C:\Users\dayneo\uncle\cousin

I hope this helps... It sure helped me :) P.S. Thanks again to DosTips! You rock!

我希望这会有所帮助...它确实帮助了我 :) PS 再次感谢 DosTips!你摇滚!

回答by Kristen

You can just concatenate them.

您可以将它们连接起来。

SET ABS_PATH=%~dp0 
SET REL_PATH=..\SomeFile.txt
SET COMBINED_PATH=%ABS_PATH%%REL_PATH%

it looks odd with \..\ in the middle of your path but it works. No need to do anything crazy :)

\..\ 在你的路径中间看起来很奇怪,但它有效。不需要做任何疯狂的事情:)

回答by George Sisco

In your example, from Bar\test.bat, DIR /B /S ..\somefile.txt would return the full path.

在您的示例中,从 Bar\test.bat, DIR /B /S ..\somefile.txt 将返回完整路径。