windows - 批处理文件 : List all files in a directory with relative paths

标签 windows batch-file cmd relative-path

关于Windows批处理文件:有没有办法列出某个目录及其子目录中的所有文件(或所有特定类型的文件),包括列表中相对于当前(或搜索)目录的路径?

例如,如果我想要当前目录和子目录下的所有.txt文件及其完整路径,我可以这样做

for /r . %%g in (*.txt) do echo %%g >> C:\temp\test.txt

dir *.txt /b /s >> C:\temp\test.txt

我会得到类似的东西

C:\test\Doc1.txt
C:\test\subdir\Doc2.txt
C:\test\subdir\Doc3.txt

如果我这样做

for /r . %%g in (*.txt) do echo %%~nxg >> C:\temp\test.txt

我会得到类似的东西

Doc1.txt
Doc2.txt
Doc3.txt

但我真正想要的是:

Doc1.txt
subdir\Doc2.txt
subdir\Doc3.txt

这可能吗?

如果我的帖子太困惑:我基本上想要 List files recursively in Linux CLI with path relative to the current directory ,但仅适用于 Windows。

最佳答案

迭代目录树和列出相对文件路径的最简单(但不是最快)的方法是使用 FORFILES .

forfiles /s /m *.txt /c "cmd /c echo @relpath"

相对路径将用前导 .\ 引用,如

".\Doc1.txt"
".\subdir\Doc2.txt"
".\subdir\Doc3.txt"


删除引号:

for /f %%A in ('forfiles /s /m *.txt /c "cmd /c echo @relpath"') do echo %%~A


删除引号和前导。\:

setlocal disableDelayedExpansion
for /f "delims=" %%A in ('forfiles /s /m *.txt /c "cmd /c echo @relpath"') do (
  set "file=%%~A"
  setlocal enableDelayedExpansion
  echo !file:~2!
  endlocal
)

或者不使用延迟扩展

for /f "tokens=1* delims=\" %%A in (
  'forfiles /s /m *.txt /c "cmd /c echo @relpath"'
) do for %%F in (^"%%B) do echo %%~F

关于windows - 批处理文件 : List all files in a directory with relative paths,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8385454/

相关文章:

c - Windows 内核驱动程序 : ZwAllocateVirtualMemory causing thread to terminate

c++ - 我应该使用线程编程来混合 2 个音频流吗?

具有多个带空格参数的 Java ProcessBuilder

windows - 查找容器 id 并停止 docker 容器的 bat 脚本语法是什么

Windows CMD 解释别名后的代码

java - 用Java清屏

windows - 使用网络驱动器作为 git 存储库

Windows 相当于/dev/random

batch-file - 如何在 .bat 批处理文件中启动 Python 虚拟环境?

windows - Windows批量上传目录和文件到FTP