包含在批处理文件脚本中用作变量的空格的文件和文件夹名称

时间:2017-03-15 19:35:38

标签: batch-file

我正在编写代码来重命名并将文件夹中的* .mp3文件移动到上层文件夹,并将文件夹名称添加到文件名中。此代码似乎适用于不包含空格的文件夹名称,但不适用。我该怎么办?

WIndows 8 - bathfile 我的代码:

@ECHO OFF
for /D %%f in (*.) do call c:\users\sina\documents\renamemp3.bat "%%f"

这次调用(renamemp3.bat):

cd %1
if ERRORLEVEL 1 goto end
for %%f in (*.mp3) do move %%f "..\%1(%%f).mp3"
cd ..
:end

3 个答案:

答案 0 :(得分:0)

@ECHO OFF
for /D %%f in (*.) do call c:\users\sina\documents\renamemp3.bat "%%~ff"

这次调用(renamemp3.bat):

@Echo off&Setlocal
cd /d "%~1"
if ERRORLEVEL 1 goto end
for %%f in (*.mp3) do move "%%f" "..\%~n1(%%~nxf).mp3"
cd ..
:end

您应该查看/ arg变量修饰符~请参阅call /?for /?

答案 1 :(得分:0)

对已经提供的脚本进行了一些更改

主要剧本:

KeyPairGenerator keyGen1 = KeyPairGenerator.getInstance("RSA");

renamemp3.bat

@For /D %%A In (*) Do @Call "%UserProfile%\Documents\renamemp3.bat" "%%~fA"

答案 2 :(得分:0)

以下是一些可能有用的建议:

  • 在文件和目录路径周围加上引号""
  • ~修饰符用于for变量(如%%~f)和参数引用(如%~1),如果它们可能包含封闭的""
  • 避免相对路径,特别是涉及多个批处理文件时(例如,由call运行)。考虑使用~f变量和参数引用的for修饰符来返回完整的绝对路径。
  • 要检索文件或目录的纯基本名称和扩展名,请始终明确指定~n~x修饰符(或组合:~nx),{{1变量或参数引用。
  • 考虑使用pushdpopd临时更改工作目录。 (尽管如此,如果您坚持使用for,请添加cd开关,以便在必要时更改驱动器。)
  • 使用以下set语法:/D;所以引号不是值的一部分。只有在读取时才用引号将值括起来。 (我知道您在代码中没有使用set "VAR=Value",但我想提一下。)

将这些规则应用于您的代码后,它可能如下所示:

主批处理文件:

set

子脚本@echo off for /D %%f in (*.) do call "c:\users\sina\documents\renamemp3.bat" "%%~ff"

renamemp3.bat

文件rem // This replaces `cd /D "%~1"`: pushd "%~1" if ErrorLevel 1 goto end for %%f in (*.mp3) do move "%%~f" "..\%~nx1(%%nxf).mp3" rem // This replaces `cd ..`: popd :end 可以简化:

renamemp3.bat

或者甚至喜欢这样:

rem /* The `&&` operator lets the following command (block) execute only in case
rem    the preceding one succeeded, hence its exit code equals zero: */
pushd "%~1" && (
    for %%f in (*.mp3) do move "%%~f" "..\%~nx1(%%nxf).mp3"
    popd
)
:end
相关问题