How to iterate through tokens in a for loop in Windows batch scripting?
I'm writing a script that allows the user to search a file and print out the parent directory for that file. So far I can get a full path from a file name but I just need the parent directory. Works fine but would like a more efficient way of iterating through the tokens.
Here is a snip-it of what I have. The file variable is the file to be searched and thePath variable is the full path to the file.
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%
Your approach cannot work reliably because a file may share the same name as one of its parent folders.
There is no need to iterate FOR /F tokens. You can get the parent folder directly using a simple FOR :-)
for %%F in ("!thePath!\..") do set "theParent=%%~nxF"
echo The parent directory is: !theParent!
Note - theParent
will be undefined (empty) if the file is in the root directory.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.