关于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/