Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

directory - Batch file - Write list of files to variable

I'd like to get a list of all files (including their absolute path) into a variable, separated by spaces. My Google-fu seems to be weak in this regard, because I keep running into issues.

I have a base directory stored in %baseDir%, and would like to parse it for files (not recursing or including sub-directories). Like I mentioned, this needs to go into a list. I'd imagine there's a nice little shortcut I could use, but a for loop and concatenation would do the trick as well.

Ideally, I'd have something like this:

echo fileList

C:file1.c C:file2.c C:file3.c
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Pretty simple:

setlocal enabledelayedexpansion enableextensions
set LIST=
for %%x in (%baseDir%*) do set LIST=!LIST! %%x
set LIST=%LIST:~1%

In fact, you find this very example also in the help for the set command, accessible via help set, complete with an explanation why the na?ve approach won't work.

To use a different set of files (rather than all), you can easily change the wildcard:

for %%x in (%baseDir%*.c) do set LIST=!LIST! %%x

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...