簡體   English   中英

嘗試使用Bat文件獲取目錄和子目錄中所有文件的行數

[英]Trying to Get A Line Count for all Files in a Directory and Sub-Directories using a Bat File

我正在嘗試獲取此bat文件,以便為我提供目錄(以及所有子目錄)中的文檔列表以及每個文檔的行數。

我已經能夠獲取下面的代碼,但是它只為我提供文件夾根目錄中的文檔,而沒有子目錄。 我搜索了很多不同的論壇,但一直找不到可行的答案。

@echo off

:start
cls
echo Enter full path to directory that you want to count files for:
set /P FilePath=
echo ..
echo ...
if exist %FilePath%\CountLines.csv del %FilePath%\CountLines.csv /q
for /f "usebackq delims=" %%a in (`find /v /c "" "%FilePath%"\*.*`) do echo %%a >> "%FilePath%"\CountLines.csv
pause()
goto start

這是我得到的輸出,這是正確的,但在子目錄中未返回文檔

MD5HASH APPEARS ONCE.csv 1174690 
Split.txt 4258 
COUNTLINESINFILES.txt 1 
@echo off
setlocal

echo Enter full path to directory that you want to count files for:

rem Get path of the directory to search.
set /P "FilePath=" || (
    >&2 echo Invalid reply.
    exit /b 1
)

rem Check if the dir path exists.
if not exist "%FilePath%\" (
    >&2 echo Invalid path.
    exit /b 1
)

echo ..
echo ...

rem Get count of lines of files in the dir path.
(
    for /r "%FilePath%" %%A in (*) do (
        find /v /c "" "%%~A"
    )
) > "%FilePath%\CountLines.csv"

echo Results:
type "%FilePath%\CountLines.csv"
pause

如果在腳本中設置變量,則setlocal可以幫助將變量保持在腳本本地。 setlocal已添加。

請考慮一下,如果用戶按return鍵 ,而不輸入任何內容,則該路徑可能是無效路徑,否則可以將以單個反斜杠開頭的路徑解釋為從驅動器的根目錄開始。 我不認為用戶可能會認為|| 是失敗檢查,如果失敗則執行括號中的代碼。

在繼續之前,請檢查所回復的路徑是否有效。

for /r循環將使用*模式進行遞歸迭代。 find將讀取每個文件,並將stdout寫入文件。 for /r的整個括號內,允許在關閉文件句柄之前將所有stdout寫入文件。

結果使用type顯示在最后。

看到for /? 幫助您了解for /r以及所有其他類型的for循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM