【问题标题】:CMD: Store the path of a file into a variable, using only the filename [duplicate]CMD:将文件的路径存储到变量中,仅使用文件名[重复]
【发布时间】:2016-12-27 23:27:19
【问题描述】:
我正在创建一个程序,允许用户“搜索”计算机中的文件,如果文件exists,它将在新目录中创建指向start 的快捷方式。可以使用任何和所有扩展。问题是,为了start某些扩展名(如.jar),我需要文件的path。
到目前为止,我看到的所有示例都没有成功帮助我解决此问题,因为它们通常需要已经给定的拆分路径。
例如。
(dir %Filename%.%extension% /b /s /a:-D)
我如何能够仅将由此给出的path 存储到变量中?
感谢任何帮助。
【问题讨论】:
标签:
batch-file
variables
cmd
path
directory
【解决方案1】:
如果您使用for 循环来处理dir 命令的输出,批处理将自动知道路径和文件名。从那里,只需使用众所周知的%~dp 语法来获取路径。
for /f "delims=" %%A in ('dir /b /s /a:-d') do echo %~dpA
d 获取驱动器,p 获取路径。
其他选项(来自for /?):
%~I - expands %I removing any surrounding quotes (")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file