windows 如何使Windows批处理文件中的for循环按名称顺序运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3606502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:09:03  来源:igfitidea点击:

How to make for loop in windows batch file run in name order

sqlwindowsloopsbatch-file

提问by newguy

I have a windows batch file that does this:

我有一个执行此操作的 Windows 批处理文件:

for %%s in (*.sql) do call

It loops through all the sql script in a folder.

In the folder the file names are like:
s4.06.01.sql
s4.07.01.sql
s4.08.01.sql
s4.10.01.sql
s5.01.sql

But the for loop goes through the files randomly (not in the name order), it first run s5.01, then s4.06, then s4.08, then s4.10, then s4.07. How can I make them run in the name order?

但是 for 循环随机遍历文件(不是按名称顺序),它首先运行 s5.01,然后是 s4.06,然后是 s4.08,然后是 s4.10,然后是 s4.07。如何让它们按名称顺序运行?

It used to work, but now it doesn't. What may cause this problem?

它曾经有效,但现在不行了。什么可能导致这个问题?

采纳答案by Lieven Keersmaekers

Jerry's answer might very well be what is causing the problem.

杰瑞的回答很可能就是导致问题的原因。

You might solve it by changing

你可以通过改变来解决它

for %%s in (*.sql) do call

for %%s in (*.sql) do call

to

for %%s in (dir"*.sql ^| sort) do call

for %%s in (dir"*.sql ^| sort) do call



Editcudo's to LonelyPixel

将 cudo编辑为 LonelyPixel

The posted solution does not work as is on a Windows 8 machine (perhaps it did back then with Windows XP but I have no idea).

发布的解决方案在 Windows 8 机器上无法正常工作(也许当时它在 Windows XP 上确实如此,但我不知道)

Following is a working solution using Windows 8 command prompt.

以下是使用 Windows 8 命令提示符的可行解决方案。

for /f "tokens=*" %%s in ('dir /b *.sql ^| sort') do echo %%s

回答by Jerry Coffin

If memory serves, it will operate on the files in the order they're returned by the file system. As such, if you run it on a disk partition that's formatted with NTFS, the names will be returned in sorted order so they'll be processed in sorted order. If the disk partition is formatted with something like FAT or FAT32, the names will be retrieved (and processed) in a more or less random order.

如果内存可用,它将按照文件系统返回的顺序对文件进行操作。因此,如果您在使用 NTFS 格式化的磁盘分区上运行它,名称将按排序顺序返回,以便按排序顺序处理它们。如果磁盘分区使用 FAT 或 FAT32 之类的格式进行格式化,则名称将以或多或少的随机顺序检索(和处理)。

回答by patman

I too had to deal with spaces in the filenames, so I added quotes around the input variable like so:

我也不得不处理文件名中的空格,所以我在输入变量周围添加了引号,如下所示:

for /f "tokens=*" %%s in ('dir /b *.sql ^| sort') do echo "%%s"

In my case it was SQLCMD, with the scripts in a subdirectory, like so:

就我而言,它是 SQLCMD,脚本位于子目录中,如下所示:

SET "machineName=localhost"
for /f "tokens=*" %%f in ('dir /b PostDeployScripts\*.sql ^| sort') do sqlcmd -E -S%machineName% -i"PostDeployScripts\%%f"