tzg*_*tzg 1 windows loops for-loop batch-file token
如何在 Windows 批处理脚本中的 for 循环中迭代令牌?
我正在编写一个脚本,允许用户搜索文件并打印出该文件的父目录。到目前为止,我可以从文件名获取完整路径,但我只需要父目录。工作正常,但需要一种更有效的方式来迭代令牌。
这是我所拥有的内容的片段。file 变量是要搜索的文件,Path 变量是文件的完整路径。
fOR /F "tokens=1-25 delims=\" %%i IN ("!thePath!") DO (
if %%j equ %file% set theParent= %%i
if %%k equ %file% set theParent= %%j
if %%l equ %file% set theParent= %%k
if %%m equ %file% set theParent= %%l
if %%n equ %file% set theParent= %%m
if %%o equ %file% set theParent= %%n
if %%p equ %file% set theParent= %%o
if %%q equ %file% set theParent= %%p
if %%r equ %file% set theParent= %%q
if %%s equ %file% set theParent= %%r
if %%t equ %file% set theParent= %%s
if %%u equ %file% set theParent= %%t
if %%v equ %file% set theParent= %%u
if %%w equ %file% set theParent= %%v
if %%x equ %file% set theParent= %%w
if %%y equ %file% set theParent= %%x
if %%z equ %file% set theParent= %%y
)
echo The parent directory is: %theParent%
Run Code Online (Sandbox Code Playgroud)
您的方法无法可靠地工作,因为文件可能与其父文件夹之一共享相同的名称。
无需迭代 FOR /F 标记。您可以使用简单的 FOR 直接获取父文件夹:-)
for %%F in ("!thePath!\..") do set "theParent=%%~nxF"
echo The parent directory is: !theParent!
Run Code Online (Sandbox Code Playgroud)
注意 -theParent
如果文件位于根目录中,则该文件将是未定义的(空)。