dos下遍历目录和文件的代码(主要利用for命令)

2019-09-19 06:47:45于丽
===== 文件夹结构 =============================================
D:test
---A Folder 1
|-----A file 1.txt

|-----A file 2.txt
|-----A file 3.txt
---B Folder 2
|-----B file 1.txt
|-----B file 2.txt
|-----B file 3.txt
|---B Folder 3
|-----B sub file 1.txt
|-----B sub file 2.txt
|-----B sub file 3.txt


@echo off
set work_path=D:test
D:
cd %work_path%
for /R %%s in (.,*) do (
echo %%s
)
pause

结果
D:test.
D:testA Folder 1.
D:testA Folder 1A file 1.txt
D:testA Folder 1A file 2.txt
D:testA Folder 1A file 3.txt
D:testB Folder 2.
D:testB Folder 2B file 1.txt
D:testB Folder 2B file 2.txt
D:testB Folder 2B file 3.txt
D:testB Folder 2B Folder 3.
D:testB Folder 2B Folder 3B sub file 1.txt
D:testB Folder 2B Folder 3B sub file 2.txt
D:testB Folder 2B Folder 3B sub file 3.txt

@echo off
set work_path=D:test
D:
cd %work_path%
for /R %%s in (.) do (
echo %%s
)
pause

结果
D:test.
D:testA Folder 1.
D:testA Folder 1A file 1.txt
D:testA Folder 1A file 2.txt
D:testA Folder 1A file 3.txt
D:testB Folder 2.
D:testB Folder 2B file 1.txt
D:testB Folder 2B file 2.txt
D:testB Folder 2B file 3.txt
D:testB Folder 2B Folder 3.
D:testB Folder 2B Folder 3B sub file 1.txt
D:testB Folder 2B Folder 3B sub file 2.txt
D:testB Folder 2B Folder 3B sub file 3.txt

那么

for /R %%s in (.,*) do (
echo %%s
)



for /R %%s in (.) do (
echo %%s
)

的区别是什么呢?
在有cd %work_path% 的时候,这两个命令执行的结果是一样的,就像我们上面举的例子。但是
for /R %%s in (.,*) do (
echo %%s
)
的批处理中没有cd %work_path% ,那么显示的将是这个批处理文件所在文件夹下面的遍历结果。


@echo off
for /R "D:test" %%s in (.) do (
echo %%s
)
pause

结果
D:test.
D:testA Folder 1.
D:testB Folder 2.
D:testB Folder 2B Folder 3.

@echo off
for /R "D:test" %%s in (.,*) do (
echo %%s
)
pause

结果
D:test.
D:testA Folder 1.
D:testA Folder 1A file 1.txt
D:testA Folder 1A file 2.txt
D:testA Folder 1A file 3.txt
D:testB Folder 2.
D:testB Folder 2B file 1.txt
D:testB Folder 2B file 2.txt
D:testB Folder 2B file 3.txt
D:testB Folder 2B Folder 3.
D:testB Folder 2B Folder 3B sub file 1.txt
D:testB Folder 2B Folder 3B sub file 2.txt
D:testB Folder 2B Folder 3B sub file 3.txt
相关文章 大家在看