How do I make a 'for' loop in the command prompt?

泪湿孤枕 提交于 2020-06-16 05:56:09

问题


I'm working with a command-line program that does image-processing, and I need to run the same command on an entire folder of images. I have heard that I can run loops in the command prompt, but I have seen all sorts of different examples online and can't figure out the syntax. The images in the folder are labled "single0.pgm, single1.pgm, single2.pgm,..." all the way to single39.pgm. The command I need to run is:

DebayerGPU.exe -demosaic DFPD_R -CPU -pattern GRBG -i single0.pgm -o single0.ppm

And I need to do that for every picture. In C it is just a simple for loop like

for (int j = 0; j<40; j++) {
    DebayerGPU.exe -demosaic DFPD_R -CPU -pattern GRBG -i singlej.pgm -o singlej.ppm
}

How do I do that in the command prompt?


回答1:


I figured it out! For anyone curious, the loop is:

for %a in (0 1 2 3 4 5 6 7 8 9 10 11 1
2 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
39) do DebayerGPU.exe -demosaic DFPD_R -CPU -pattern GRBG -i single%a..pgm -o si
ngle%a.ppm



回答2:


for /l %a in (0,1,39) do DebayerGPU.exe -demosaic DFPD_R -CPU -pattern GRBG -i single%a..pgm -o single%a.ppm

is less prone to typos. This command runs happily directly from the prompt, but if it's a line within a batch file, you'd need to double the % for each instance of the metavariable %a (i.e. %a becomes %%a within a batch file.




回答3:


Here is a good short explanation of for loops, with examples. http://www.robvanderwoude.com/for.php Take a note of the 2 important key points:

  1. The code you write in command prompt will not work when you put it in batch files. The syntax of loops is different in those 2 cases due to access to variables as %%A instead of %A
  2. Specifically for your problem it is easier do do dir *.pgm and than run a for loop over all the files. Thus your program will work for any amount of files and not just hard coded 40. This can be done as explained here: Iterate all files in a directory using a 'for' loop


来源:https://stackoverflow.com/questions/18070292/how-do-i-make-a-for-loop-in-the-command-prompt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!