文件系统的批处理脚本:在另一个嵌套的for循环

时间:2015-10-30 00:19:17

标签: variables batch-file for-loop nested

过去4-5小时我花了一些时间来修复我的脚本并尝试了几件事,但它仍然无法正常工作。这是工作部分:

    @echo off
    rem automatically sort MP3s into an existing structure or add folders if needed
    rem example of MP3-file pattern: Wu-Tang Clan - Gravel Pit (LP Version Clean).mp3

    SETLOCAL

    rem set variables
    SET "source=g:\music\folder"
    SET "str=Wu-Tang Clan - Gravel Pit (LP Version Clean).mp3"
    SET "test=%source%\%str%"

    rem split the filename from the remaining path. Take the left part
    rem and assign it to %band% while the right part gets assigned to %song%
    FOR /f "delims=" %%i IN ("%test%") DO SET "result=%%~nxi"

    SET "band=%result: - =" & SET "song=%"

    rem If there is no such folder (%band%), create it
    IF not exist "%source%\%band%" MD "%source%\%band%"

    rem As soon as there definetely is a fitting folder
    rem move the file over there.
    MOVE /-Y "%source%\%result%" "%source%\%band%"

下一步是通过for循环增强代码,这样我就不必编辑每个3k +文件的脚本了;)

我努力让这段代码得以实现,但失败了:         @echo关闭         SETLOCAL

    SET "source=g:\music\folder"

    FOR %%f IN (%source%\*.mp3) DO (
    echo %%f

    FOR /f "delims=" %%i IN ("%%f") DO SET "result=%%~nxi"

    SET "band=!result: - =" & SET "song=%"

    IF not exist "%source%\%band%" MD "%source%\%band%"

    MOVE /-Y "%source%\%result%" "%source%\%band%"
    )
    pause

所以我添加了一个for循环,并且%% f首先被正确填充,并且不在下一个for循环中。

    FOR %%f IN (%source%\*.mp3) DO (
    echo %%f

导致:“g:\ music \ folder \ Wu-Tang Clan - Gravel Pit(LP版本清洁).mp3”

就像它应该的那样。但在那之后

    FOR /f "delims=" %%i IN ("%%f") DO SET "result=%%~nxi"

结果,并且每个后续变量都是空的。

我尝试用第二个变量作为'帮助'来修复它:

    FOR %%f IN (%source%\*.mp3) DO (
    SET "helper=%%f"
    FOR /f "delims=" %%i IN ("%helper%") DO SET "result=%%~nxi"

在我读完之后,甚至添加了'enabledelayedexpansion',然后去了

    FOR /f "delims=" %%i IN ("!helper!") DO SET "result=%%~nxi"

仍然无效。

现在我真的需要一些帮助,我真的很感激它:)

问凤凰

1 个答案:

答案 0 :(得分:1)

下一个代码段可以正常工作。请注意,SET "band=%result: - =" & SET "song=%"技巧无法使用!延迟扩展执行,而不像% - 扩展。因此,该命令被移动到:myset子例程并通过call command执行。

@echo off
SETLOCAL EnableExtensions EnableDelayedExpansion
SET "source=g:\music\folder"
FOR %%f IN (%source%\*.mp3) DO (
  echo %%f
  FOR /f "delims=" %%i IN ("%%f") DO SET "result=%%~nxi"
  call :myset
  IF not exist "%source%\!band!" MD "%source%\!band!"
  MOVE /-Y "%source%\!result!" "%source%\!band!"
)
goto :skipMyset

:myset
  SET "band=%result: - =" & SET "song=%"
goto :eof

:skipMyset
pause

资源(必读):