Home > OS >  batch script loop in win cmd
batch script loop in win cmd

Time:05-05

I need to merge multiple ".ts" files in each directory. The file structure is like this: file structure

I've tried loop code and it worked well in a one-layer structure:

for /l %%x in (1,1,24) do (
    copy /b %%x\*.ts new_%%x.ts
)
pause

I tried to add another loop to run a double-layer structure, it won't work in the following code:

for /l %%x in (1,24,49) do (
    for /l %%a in (%%x,1,%%x 23) do (
        copy /b %%x\%%a\*.ts \%%x\new_%%a.ts
    )
)

The problem is the values can't be summed here:

%%x 23

Then I tried to calculate the value before putting it in the second loop:

for /l %%x in (1,24,49) do (
    set /a endvalue=%%x 23
    for /l %%a in (%%x,1,endvalue) do (
        copy /b %%x\%%a\*.ts \%%x\new_%%a.ts
    )
)

And the code still doesn't work.

Did I miss something? How can I fix it?

Thanks, CJ

CodePudding user response:

Use delayed environment variable expansion

@echo off
setlocal EnableDelayedExpansion
for /l %%x in (1,24,49) do (
    set /a beginvalue=%%x
    set /a endvalue=%%x   23
    for /l %%a in (!beginvalue!,1,!endvalue!) do (
        echo %%a
    )
)
  • Related