Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

windows - Batch files: List all files in a directory with relative paths

Concerning Windows batch files: Is there a way to list all the files (or all of a specific type) in a certain directory and its subdirectories, including the paths relative to the current (or the search) directory in the list?

For example, if I want all the .txt files in the current directory and subdirectories with their full paths, I can do

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

or

dir *.txt /b /s >> C:empest.txt

and I will get something like

C:estDoc1.txt
C:estsubdirDoc2.txt
C:estsubdirDoc3.txt

If I do

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

I will get something like

Doc1.txt
Doc2.txt
Doc3.txt

But what I really want is:

Doc1.txt
subdirDoc2.txt
subdirDoc3.txt

Is it possible?

If my post is too confusing: I basically want List files recursively in Linux CLI with path relative to the current directory, but just for Windows.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest (but not the fastest) way to iterate a directory tree and list relative file paths is to use FORFILES.

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

The relative paths will be quoted with a leading . as in

".Doc1.txt"
".subdirDoc2.txt"
".subdirDoc3.txt"


To remove quotes:

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


To remove quotes and the leading .:

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
)

or without using delayed expansion

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...