windows 如何在批处理文件中获得 dirname() 的等效项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/778135/
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:16:45  来源:igfitidea点击:

How do I get the equivalent of dirname() in a batch file?

windowscommand-linebatch-file

提问by arathorn

I'd like to get the parent directory of a file from within a .batfile. So, given a variable set to "C:\MyDir\MyFile.txt", I'd like to get "C:\MyDir". In other words, the equivalent of dirname()functionality in a typical UNIX environment. Is this possible?

我想从.bat文件中获取文件的父目录。所以,给定一个变量设置为"C:\MyDir\MyFile.txt",我想得到"C:\MyDir"。换句话说,相当于dirname()典型 UNIX 环境中的功能。这可能吗?

回答by Joey

for %%F in (%filename%) do set dirname=%%~dpF

This will set %dirname%to the drive and directory of the file name stored in %filename%.

这将设置%dirname%为存储在%filename%.

Careful with filenames containing spaces, though. Either they have to be set with surrounding quotes:

但是要小心包含空格的文件名。要么必须使用周围的引号设置它们:

set filename="C:\MyDir\MyFile with space.txt"

or you have to put the quotes around the argument in the forloop:

或者你必须在for循环中的参数周围加上引号:

for %%F in ("%filename%") do set dirname=%%~dpF

Either method will work, both at the same time won't :-)

任何一种方法都可以,但同时都不会:-)

回答by Anders

If for whatever reason you can't use FOR (no Command Extensions etc) you might be able to get away with the ..\ hack:

如果由于某种原因您不能使用 FOR(没有命令扩展等),您可能可以摆脱 ..\ hack:

set file=c:\dir\file.txt
set dir=%file%\..\

回答by Ben Key

The problem with the for loop is that it leaves the trailing \ at the end of the string. This causes problems if you want to get the dirname multiple times. Perhaps you need to get the name of the directory that is the grandparent of the directory containing the file instead of just the parent directory. Simply using the for loop technique a second time will remove the \, and will not get the grandparent directory.

for 循环的问题在于它将尾随的 \ 留在字符串的末尾。如果您想多次获取目录名,这会导致问题。也许您需要获取目录的名称,该目录是包含文件的目录的祖父目录,而不仅仅是父目录。简单地再次使用 for 循环技术将删除 \,并且不会获得祖父目录。

That is you cannot simply do the following.

那就是您不能简单地执行以下操作。

set filename=c:\t.txt
for %%F in ("%filename%") do set dirname=%%~dpF
for %%F in ("%dirname%") do set dirname=%%~dpF

This will set dirname to "c:\1\2\3", not "c:\1\2".

这会将目录名设置为“c:\1\2\3”,而不是“c:\1\2”。

The following function solves that problem by also removing the trailing \.

以下函数还通过删除尾随的 \ 来解决该问题。

:dirname file varName
    setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
    SET _dir=%~dp1
    SET _dir=%_dir:~0,-1%
    endlocal & set %2=%_dir%
GOTO :EOF

It is called as follows.

它被称为如下。

set filename=c:\t.txt
call :dirname "%filename%" _dirname
call :dirname "%_dirname%" _dirname