Windows bat: loop files in directories

淺唱寂寞╮ 提交于 2019-12-31 05:25:25

问题


I'm working on Windows. I have many jpg files in subdirectories of a directory. I don't know exactly the architecture of the directory, meaning that I don't know how many levels the subdirectories have. What I need to do is to process jpg files according to their paths. Here is an example:

dir
 |---sub dir1
 |      |-----sub dir11
 |               |-----a.jpg
 |               |-----b.jpg
 |---sub dir2
        |-----c.jpg
        |-----d.jpg

So I need to execute commands as below:

process.bat C:\dir\sub dir1\sub dir11\a.jpg C:\dir\sub dir1\sub dir11\b.jpg
process.bat C:\dir\sub dir2\c.jpg C:\dir\sub dir2\d.jpg

I don't know how to write such a bat file especially a bat processing paths contains spaces. I don't know if spaces will make some trouble.

I've tried as below but it doesn't work:

@Echo off&SetLocal EnableExtensions EnableDelayedExpansion

For /d %%A in (C:\dir\*) Do (
    Set "Files="
    For /f %%B in ("%%~fA\*.jpg") Do Set Files=!Files! "%%~fB"
    If defined Files echo process.bat %%~fA\*.jpg
)

pause

When I execute the script, I get the result as below:

process.bat C:\dir\sub dir1\*.jpg
process.bat C:\dir\sub dir2\*.jpg

It seems that * is regarded as a normal character.


回答1:


@Echo off&SetLocal EnableExtensions EnableDelayedExpansion

For /d %%A in (C:\dir\*) Do (
    Set "Files="
    For /F "delims=" %%B in ('dir /S /B "%%~fA\*.jpg"') Do Set Files=!Files! "%%~fB"
    If defined Files echo process.bat !Files!
)

pause



回答2:


If defined Files echo process.bat !files!

should solve the problem - but whether process.bat will co-operate is yet to be determined. Would need you to list process.bat if required.



来源:https://stackoverflow.com/questions/44402963/windows-bat-loop-files-in-directories

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