如何让 for 循环处理带有空格的单行逗号分隔字符串
我有一个包含文件列表的批处理文件的输入(这都是一行,也是bat文件的许多输入之一):
"\\Server\my directory name\subdir,\\Server \my 目录名称\subdir2,\\Server\my 目录名称\subdir3"
我想迭代此列表并对列表中的每个目录执行命令。但是,当我指定 delims= 时,它会将空格视为分隔符,即使文档说“指定分隔符集。这会替换空格和制表符的默认分隔符集”。看起来并没有取代,只是增加了。我尝试过用 backq 搞乱,但这似乎不起作用,因为输入已经被引用了。
我能得到的最接近的是
for /f "tokens=1-8 delims=," %%d in ("%destPath%") do (
echo %%d
echo %%e
echo .
)
但我这里有一组未知的输入,所以我可能会收到 12 个目录,并且不希望命令执行有重复的行(循环体中同一行 n 次),似乎违背了 for 循环的目的。
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不控制输入,那么使用逗号作为分隔符并不是一个好主意,因为它在文件名中也有效。如果您可以使用 * 或类似的东西,您可以确保您能够处理所有有效路径。
我决定不再过多地对抗 FOR 命令,而是选择了递归“子函数”
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"
除了 DOS (cmd.exe) 之外,另一个更好的选择(无需任何下载)是使用 vbscript。这是一个
另存为 myscript.vbs 的示例,您可以在命令行上
增强脚本以在这些目录中执行您想要的操作,或者使用批处理来获取这些目录。例如
besides DOS (cmd.exe), the other better alternative , (without any download), is using vbscript. here's an example
save as myscript.vbs and on the command line
you can enhance the script to do what you want inside those directories, or use the batch to grab those directories. eg