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

时间:2015-01-20 08:46:02

标签: windows batch-file

我试图以递归方式循环遍历文件夹中的所有文件。 我需要读取文件名,abcd_somethingone_pqrs.csv是文件名模式。我需要创建一个名为somethingone的文件夹(如果文件夹不存在)并将文件移动到该文件夹​​中。我已经开始在.bat中编写以下代码。

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

line1正确打印文件夹中的文件名。但是当我将它读入新变量newloc时,line4始终只打印最后一个文件的名称。任何人都可以在这里意识到这里出了什么问题,或者给我一个方法来做到这一点。

1 个答案:

答案 0 :(得分:0)

编辑:完全改变了我的答案,并试图彻底解决你的整体问题,而不仅仅是你坚持的事情。

您必须将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
    )
)

<小时/> 您需要启用延迟扩展,以便for循环内的变量值正确传播。

setlocal enabledelayedexpansion
for /R D:\MOE\MRs\batchfiles\01\ %%F in (*.*) do (
    echo %%~nF
    set newloc=%%~nF
    echo !newloc!
) 
相关问题