我试图计算目录中每个文本文件的行数,条件是具有相同文件名的文本文件也存在于第二个目录或其子目录中。该脚本应计算两个文件的行数。这是我的代码:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /R "C:\Users\ABC\Documents\" %%W IN (*.txt) DO (
FOR /R "C:\Users\XYZ\Documents\" %%J IN ("%%~nxW") DO (
IF EXIST "%%J" (
set "firstfile=findstr /R /N "^^" "%%W" | find /C ":""
FOR /F %%G in ('!firstfile!') do set firstfilelines=%%G
set "secondfile=findstr /R /N "^^" "%%J" | find /C ":""
FOR /F %%H in ('!secondfile!') do set secondfilelines=%%H
ECHO %%W has !firstfilelines! lines.
ECHO %%J has !secondfilelines! lines.
)
)
)
pause
它计算第一个目录C:\ Users \ ABC \ Documents \中的文本文件行,但不计入C:\ Users \ XYZ \ Documents \中的文本文件行,因为findstr无法将%% J的值识别为文件路径,因为它在文件名周围加上引号,如C:\ Users \ XYZ \ Documents \ folder \" file.txt"。我如何摆脱这些报价?
答案 0 :(得分:1)
dir /s /b
在第二个文件夹中构建文件列表find /c /v "" filename
更快地计算行数set /a
修剪数字分配中的空格@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
set "folder1=C:\Users\ABC\Documents\"
set "folder2=C:\Users\XYZ\Documents\"
FOR /R "%folder1%" %%W IN (*.txt) DO (
FOR /f "delims=" %%J in ('dir /s /b "%folder2%\%%~nxW"') DO (
IF EXIST "%%J" (
FOR /F "tokens=3 delims=:" %%G in ('find /c /v "" "%%W"') do set /a L1=%%G
FOR /F "tokens=3 delims=:" %%G in ('find /c /v "" "%%J"') do set /a L2=%%G
ECHO %%W has !L1! lines.
ECHO %%J has !L2! lines.
)
)
)
pause