简体   繁体   English

Windows批处理文件错误传递变量(.bat)

[英]Windows batch file error passing variable (.bat)

I'm trying to loop recursively through all the files inside a folder. 我试图递归遍历文件夹内的所有文件。 I need to read the file name, abcd_somethingone_pqrs.csv is the file name pattern. 我需要读取文件名,abcd_somethingone_pqrs.csv是文件名模式。 I need to create a folder (if the folder does not exist) named somethingone and move the file into that folder. 我需要创建一个名为“ oneone”的文件夹(如果该文件夹不存在),然后将文件移动到该文件夹​​中。 I have started writing the following code in a .bat. 我已经开始在.bat中编写以下代码。

FOR /R D:\MOE\MRs\batchfiles\01\ %%F in (*.*) do ( 
echo %%~nF
set newloc=%%~nF
echo %newloc%
) 

The line1 prints the filenames in the folder correctly. 第1行正确打印了文件夹中的文件名。 But when I read it to the new variable newloc, always the line4 prints only the last file's name. 但是,当我将其读取到新变量newloc时,第4行始终仅输出最后一个文件的名称。 Can anyone please realize what's going wrong here or propose me a method to do this. 任何人都可以请您了解这里出了什么问题或向我提出一种解决方法。

EDIT: Totally changed my answer and actually attempted to completely solve your overall problem instead of just the thing you were stuck on. 编辑:完全改变了我的答案,实际上试图完全解决您的总体问题,而不仅仅是您坚持的事情。

You'll have to update target_dir to wherever you want the files to go. 您必须将target_dir更新到您想要文件放到的任何位置。

@echo off
setlocal enabledelayedexpansion

set source_dir=D:\MOE\MRs\batchfiles\01\
set target_dir=D:\something\

:: Recursively search the source directory for files
for %%A in (somethingone somethingtwo somethingthree) do (
    for /F "delims=" %%B in ('dir /a:-d /s /b %source_dir%*%%A*') do (
        REM if the directory does not exist, make it
        if not exist %target_dir%%%A mkdir %target_dir%%%A

        move %%B %target_dir%%%A
    )
)


You need to enable delayed expansion so that the variable value inside the for loop will propagate correctly. 您需要启用延迟扩展,以便for循环内的变量值可以正确传播。

 setlocal enabledelayedexpansion for /RD:\\MOE\\MRs\\batchfiles\\01\\ %%F in (*.*) do ( echo %%~nF set newloc=%%~nF echo !newloc! ) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM