仅列出子目录而不是完整目录

时间:2016-07-02 11:59:08

标签: windows batch-file cmd

我正在使用Windows命令解释程序的内部命令来获取当前目录和子目录中的所有文件:

dir /s /b /o:gn > output.txt

它给了我一个输出:

C:\ParentDir\CurrentDir\ChilderDir\AnApp.exe

我想要输出:

ChilderDir\AnApp.exe

如何获取没有当前目录路径的文件和目录列表?

1 个答案:

答案 0 :(得分:2)

此批处理代码可用于获取没有基本路径的目录和文件名列表。

@echo off
setlocal EnableExtensions EnableDelayedExpansion

rem The environment variable CD holds path of current directory without a
rem backslash at end, except the current directory is the root directory
rem of a drive. This must be taken into account to get current directory
rem path with a backslash at end.

if "%CD:~-1%" == "\" (
    set "CurrentDirectory=%CD%"
) else (
    set "CurrentDirectory=%CD%\"
)

rem Delete the output file in current directory if already existing.
if exist output.txt del /F output.txt

rem Get recursive the directory and file names not having system or hidden
rem attribute set and remove from each directory and file name the current
rem directory path. With DIR parameter /A directories and files with hidden
rem or system attribute would be also included in the list. The output file
rem output.txt is also in the list.

for /F "delims=" %%I in ('dir /B /S /O:GN 2^>nul') do (
    set "FileNameWithFullPath=%%I"
    echo !FileNameWithFullPath:%CurrentDirectory%=!>>output.txt
)

endlocal

要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。

  • echo /?
  • endlocal /?
  • for /?
  • if /?
  • rem /?
  • set /?
  • setlocal /?

命令 DIR 输出的错误消息,用于处理 STDERR ,当前目录中没有任何隐藏/系统目录或文件被重定向到设备 NUL 使用2>nul来抑制它,其中必须使用>转义重定向运算符^,以便在执行 DIR 时应用,而不是将其解释为重定向在命令行中的无效位置命令 FOR ,这将导致执行时出现语法错误消息。另请参阅Microsoft文章Using command redirection operators