how do I get a for loop to work on a single line comma delimited string with spaces
I've got an input to a batch file that contains a list of files (this is all one line and one of many inputs to the bat file):
"\\Server\my directory name\subdir,\\Server\my directory name\subdir2,\\Server\my directory name\subdir3"
I'd like to iterate this list and perform a command on each directory in the list. However, when I specify delims=, it treats the spaces as delimiters, even though the docs say "Specifies a delimiter set. This replaces the default delimiter set of space and tab." Doesn't seem to be replacing, just seems to be adding to. I've tried messing around with backq but that doesn't seem to work, since the input is already quoted.
开发者_如何转开发The closest I can get is
for /f "tokens=1-8 delims=," %%d in ("%destPath%") do (
echo %%d
echo %%e
echo .
)
But I have an uknown set of inputs here, so I could be getting 12 directories coming in and don't want to have a repeated line for the command execution (same line n times in the loop body), seems to defeat the purpose of a for loop.
Related: How do I get a for loop to work with a comma delimited string?
Using comma as a separator is not a good idea if you don't control the input since it is also valid in filenames. If you could use * or something like that, you could be sure that you are able to handle all valid paths.
I decided not to fight the FOR command too much, instead I opted for a recursive "sub function"
:printThem
for /F "tokens=1,* delims=," %%A in ("%~1") DO (
echo.Path: %%A
call :printThem "%%~B"
)
@goto :EOF
call :printThem "\\Server\my directory name\subdir,\\Server\my directory name\subdir2,\\Server\my directory name\subdir3"
besides DOS (cmd.exe), the other better alternative , (without any download), is using vbscript. here's an example
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
strFile = objArgs(0)
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
s = Split(strLine,",")
For Each strDir In s
WScript.Echo strDir
'Set objFolder = objFS.GetFolder(strDir)
'WScript.Echo strDir & " modified date is " & objFolder.DateLastModified
'Set objFolder = Nothing
Next
Loop
save as myscript.vbs and on the command line
C:\test>cscript //nologo myscript.vbs file
\\Server\my directory name\subdir
\\Server\my directory name\subdir2
\\Server\my directory name\subdir3
you can enhance the script to do what you want inside those directories, or use the batch to grab those directories. eg
@echo off
for /F "delims=" %%f in ('cscript //nologo test.vbs file') do (
echo do something with %%f
)
精彩评论