dos下遍歷目錄和文件的代碼(主要利用for命令)
2020-06-09 13:54:17
供稿:網友
===== 文件夾結構 =============================================
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:/test/A Folder 1/.
D:/test/A Folder 1/A file 1.txt
D:/test/A Folder 1/A file 2.txt
D:/test/A Folder 1/A file 3.txt
D:/test/B Folder 2/.
D:/test/B Folder 2/B file 1.txt
D:/test/B Folder 2/B file 2.txt
D:/test/B Folder 2/B file 3.txt
D:/test/B Folder 2/B Folder 3/.
D:/test/B Folder 2/B Folder 3/B sub file 1.txt
D:/test/B Folder 2/B Folder 3/B sub file 2.txt
D:/test/B Folder 2/B Folder 3/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:/test/A Folder 1/.
D:/test/A Folder 1/A file 1.txt
D:/test/A Folder 1/A file 2.txt
D:/test/A Folder 1/A file 3.txt
D:/test/B Folder 2/.
D:/test/B Folder 2/B file 1.txt
D:/test/B Folder 2/B file 2.txt
D:/test/B Folder 2/B file 3.txt
D:/test/B Folder 2/B Folder 3/.
D:/test/B Folder 2/B Folder 3/B sub file 1.txt
D:/test/B Folder 2/B Folder 3/B sub file 2.txt
D:/test/B Folder 2/B Folder 3/B 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:/test/A Folder 1/.
D:/test/B Folder 2/.
D:/test/B Folder 2/B Folder 3/.
代碼如下:
@echo off
for /R "D:/test" %%s in (.,*) do (
echo %%s
)
pause
結果
D:/test/.
D:/test/A Folder 1/.
D:/test/A Folder 1/A file 1.txt
D:/test/A Folder 1/A file 2.txt
D:/test/A Folder 1/A file 3.txt
D:/test/B Folder 2/.
D:/test/B Folder 2/B file 1.txt
D:/test/B Folder 2/B file 2.txt
D:/test/B Folder 2/B file 3.txt
D:/test/B Folder 2/B Folder 3/.
D:/test/B Folder 2/B Folder 3/B sub file 1.txt
D:/test/B Folder 2/B Folder 3/B sub file 2.txt
D:/test/B Folder 2/B Folder 3/B sub file 3.txt