Use nested loop to copy files in filelist to folders in folderlist, with batch

不羁岁月 提交于 2019-12-12 04:46:33

问题


I want to simultaneously read from a file list and a folder list and copy each file into each folder, with a file rename.

Below is my original code. The outside loop doesn't increment. I've tried every which way to apply what I've read about loops and delayed expansion but nothing has worked.

Can someone please tell me how to fix the code or what to use instead?

EDIT to clarify problem: With each iteration, "echo src" echoes 1st line in Filelist.txt. Never changes. On the other hand, "echo dest" does go through folderlist.txt as expected (desired).

@echo off
setlocal enabledelayedexpansion
:: var is set in calling routine
SET "newname=%var%_filename_0.jpg"   
    FOR /F  %%G IN (Filelist.txt) DO (
    FOR /F %%H IN (Folderlist.txt) DO (
        SET src=%%G
        SET dest=%%H
            echo src is !src!
            echo dest is !dest!
            REM Here with each iteration do a copy and rename
            :: copy "!src!" "!dest!\%newname%"  1>nul
  )
)

回答1:


The main problem in your code is not the syntax, but the concept. Your code reads a line from list of files and then, for this line, reads all the lines in the folder list.

If you have nested for loops, for each iteration of the outer for all iterations of the inner loop are executed.

If you need a synchronized line read from the two files, you need something like

@echo off
    setlocal enableextensions disabledelayedexpansion

    < files (
        for /f "delims=" %%a in (folders) do (
            set /p "myFile="
            setlocal enabledelayedexpansion
            for /f "delims=" %%b in ("!myFile!") do (
                endlocal
                echo %%a %%b
            )
        )
    )

That is, the folder list is read with the for command, and the file list, is read from the standard input with a set /p. Since we are redirecting the file list as input, the set /p will get its data from it.



来源:https://stackoverflow.com/questions/25519598/use-nested-loop-to-copy-files-in-filelist-to-folders-in-folderlist-with-batch

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