Yves
Yves

Reputation: 12371

Windows bat: loop files in directories

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.

Upvotes: 0

Views: 140

Answers (2)

Yves
Yves

Reputation: 12371

@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

Upvotes: 1

Magoo
Magoo

Reputation: 79982

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.

Upvotes: 0

Related Questions