Search code examples
batch-filenotepad++

Batch loop through file


I'm trying to make a batch process in Notepad++ that will count the number of duplicate lines from text selected.

So far I have Notepad++ working fine

NPE_CONSOLE v+
CLS
ECHO $(CURRENT_WORD)
CON_SAVETO "H:\tmp.txt"
NPE_CONSOLE v-

This scripts saves the selected text into tmp.txt with the only issue being it includes, at the bottom, CON_SAVETO "H:\tmp.txt" but I can live with that for now.

EDIT: Also, I do not think Notepad++ is the issue here since I try running the batch file from cmd line and get the same errors/problems. I also tried setting the tmp.txt file manually and still same issues.

My batch file is what is causing issues:

::@ECHO OFF
CD "H:\"
SET counter=0
SET prev=a

FOR /F "tokens=*" %%L IN (tmp.txt) DO (
    SET blnOut=0
    SET curLine="%%L"

    IF /I %prev%==%curLine% (
        SET counter=%counter%+1
        SET blnOut=1
    )
    IF %blnOut%==0 (
        IF %prev%==a (
            SET counter=%counter%+1
            SET blnOut=1
        )
        IF %blnOut%==0 (
            ECHO %curLine%- %counter%
            SET counter=1
        )
    )
    SET prev=%curLine%
)

I've tried everything I can think of, including splitting off the process into a function, but I keep getting errors like Unexpected ) or, if it does run, it does not loop through the file.

Currently, this is tmp.txt:

1
2
3
4
5
6
7
8
1
4
5
8
4
3
4
4
5

So Ideal output is:

1 - 2
2 - 1
3 - 2
4 - 5
5 - 3
6 - 1
7 - 1
8 - 2

Solution

  • @ECHO OFF
    SETLOCAL enabledelayedexpansion
    FOR %%i IN (prev) DO SET "%%i="
    FOR /f "delims=" %%i IN ('sort ^<temp.txt') DO (
     IF DEFINED prev (
      IF "!prev!"=="%%i" (SET /a count+=1) ELSE (
      ECHO !prev! - !count!
      SET "prev="
      )
     )
     IF NOT DEFINED prev (
      SET prev=%%i
      SET /a count=1
     )
    )
    ECHO %prev% - %count%
    

    Here's my version. Sort the input file to group like lines together, then when the line-contents change, display the previous contents and count and reset the counter and record of previous line.