0

I am trying to count the lines of each text file in a directory on the condition that a text file with the same filename also exists in a second directory or one of its subdirectories. The script should count the lines of both files. Here's my code:

@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

It counts the lines of text files in the first directory C:\Users\ABC\Documents\ but not in C:\Users\XYZ\Documents\ because findstr cannot recognize the value of %%J as a file path because it puts quotes around the filename as in C:\Users\XYZ\Documents\folder\"file.txt". How do I get rid of these quotes?

8
  • 1
    The second for won't work without * in the search pattern. Commented Nov 24, 2015 at 17:20
  • But it does. Try it. My only problem is the stubborn quotes. Commented Nov 24, 2015 at 17:22
  • 1
    It doesn't work correctly, it lists all the found paths and blindly appends the file name even if it doesn't exist there. Well, thanks to if exist check it's not a problem. Commented Nov 24, 2015 at 17:23
  • 1
    IF EXIST "%%~J" and "%%~W" and similar. Just add a tilde where you want the surrounding quotation marks stripped. Commented Nov 24, 2015 at 17:23
  • @rojo I already tried it. It did not strip the quotes but it stripped the last backslash in the file path as in C:\Users\XYZ\Documents\folder"file.txt" Commented Nov 24, 2015 at 17:29

1 Answer 1

1
  • Use dir /s /b to build a list of files in the second folder
  • Use find /c /v "" filename to count the lines faster
  • Use set /a to trim the spaces in the assignment of the number

@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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! You are a lifesaver!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.