使用EnableDelayedExpansion时,更正变量修饰符的语法

时间:2013-10-11 16:20:13

标签: windows variables batch-file for-loop

我希望能够执行%~p只能看到文件的路径。但是在循环中使用它时,我无法获得正确的语法(使用EnableDelayedExpansion)

这是我的代码:

@echo off
set "dir1=%TMP%\opt"
set "dir2=c:\opt"
set "empty="

setlocal EnableDelayedExpansion
for /f %%F in ('dir  /a:-d /s /b /r "%dir1%"') do (
  set "file_path=%%F"
  set "file_name=%%~nF"
  set "new_path=!file_path:%dir1%=%dir2%!"
  set "new_path=!new_path:!file_name!=%empty%" //This command is problematic
  echo !new_path!
)
endlocal

任何方式让我这样做?

1 个答案:

答案 0 :(得分:2)

以下是获取和替换文件路径的方法。

@echo off
setlocal EnableDelayedExpansion

set "dir1=%TMP%\opt"
set "dir2=c:\opt"

pushd "%dir1%" && for /f %%F in ('dir /a:-d /b /r /s') do (
    set "file_path=%%~dpF"
    set "new_path=!file_path:%dir1%=%dir2%!"
    echo !new_path!
) & popd

endlocal
exit /b 0

解释

主要的变化是对变量使用~dp修饰符,导致它只获取没有文件名的完整文件路径。

你对dir1替换的使用是正确的,这是你的文件名替换是坏的。通过使用~dp修饰符,我们可以完全跳过文件名替换部分。

pushd仅在for循环开始设置工作目录之前调用一次。

操作实例:

  • 将工作目录设置为dir1
  • 遍历该目录和子目录中的所有文件。
  • 对于每个文件,只获取文件路径C:\Path\opt\sub而不是C:\path\opt\sub\file.ext
  • C:\path\opt替换为C:\opt
  • 显示结果。
  • popd会将工作目录恢复为pushd之前的状态。

以下是for /?帮助文本中所有变量修饰符的列表。

In addition, substitution of FOR variable references has been enhanced.
You can now use the following optional syntax:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

The modifiers can be combined to get compound results:

%~dpI       - expands %I to a drive letter and path only
%~nxI       - expands %I to a file name and extension only
%~fsI       - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
               environment variable for %I and expands to the
               drive letter and path of the first one found.
%~ftzaI     - expands %I to a DIR like output line

In the above examples %I and PATH can be replaced by other valid
values.  The %~ syntax is terminated by a valid FOR variable name.
Picking upper case variable names like %I makes it more readable and
avoids confusion with the modifiers, which are not case sensitive.