【问题标题】:batch script for file system: use of for-loop variable in another nested for-loop文件系统的批处理脚本:在另一个嵌套的 for 循环中使用 for 循环变量
【发布时间】:2015-10-30 00:19:17
【问题描述】:

过去 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 关闭 本地设置

    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 Version Clean).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"

还是不行。

现在我真的需要一些帮助,非常感谢:)

向凤凰致敬

【问题讨论】:

  • 您需要delayed expansion 将您的代码放入for 循环并使用!variable! 扩展语法;否则,当声明%variable% 时,它将扩展到整个循环执行之前 存在的值;

标签: variables batch-file for-loop nested


【解决方案1】:

下一个代码 sn-p 可以工作。请注意,SET "band=%result: - =" & SET "song=%" 技巧不能使用 ! 延迟扩展来执行,这与 %-expansion 不同。因此,该命令被移至: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

资源(必读):

【讨论】:

  • 一个子程序!!!!当然-.- 现在它完成了它的工作。非常感谢 JosefZ 快速而正确的回答,让我很开心:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 2013-08-08
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
相关资源
最近更新 更多