Search code examples
regexwindowsbatch-filecmdfindstr

Writing .txt files from lines 1 to i


I am very close to my answer, but I cant seem to find it. I am using the Findstr function in a batch file to narrow now an entire directory to just one file.

cd ...
findstr /s /m "Desktop" *class.asasm >results1.txt
findstr /m /f:results1.txt "Production" *class.asasm >results2.txt
findstr /n /f:results2.txt "Capabilities" *class.asasm >results3.txt

TASK 1: I need to figure out a way to make findstr search backwards for a fourth string from the line number the third line was found on

TASK 2: I need to write lines 1-the one we arrive at of the file in results2.txt the insert a .txt file. Then write the rest of the original lines.

I am writing an application in VB.Net with Visual Studios and I am having a difficult time figuring out how to complete this process. I am currently having better luch with having the application run batch files that are written within the application.


Solution

  • The correct solution is to find a tool that does this properly. batch/CMD does not.

    Here's a script that tells you the line numbers of the 3rd and 4th match. It's probably not exactly what you want, but it is a demonstration of how one can effectively work with line numbers.

    @ECHO OFF
    SETLOCAL ENABLEDELAYEDEXPANSION
    
    SET FILE=TestFile.txt
    
    SET _LINENO=1
    SET _MATCHNO=0
    SET _THIRDLINENUM=
    SET _FOURTHLINENUM=
    FOR /F %%l IN (%FILE%) DO (
       ECHO %%l | FINDSTR "Target" %_TMP% >NUL
       IF NOT ERRORLEVEL 1 (
          SET /A _MATCHNO=!_MATCHNO!+1
          IF !_MATCHNO!==3 SET _THIRDLINENUM=!_LINENO!
          IF !_MATCHNO!==4 SET _FOURTHLINENUM=!_LINENO!
       )
       SET /A _LINENO=!_LINENO!+1
    )
    
    @ECHO %_THIRDLINENUM% : %_FOURTHLINENUM%
    

    Here's what's in TestFile.txt

    abcdefg
    bcdefgh
    Target 1
    cdefghi
    defghij
    fghijkl
    Target 2
    ghijklm
    hijklmn
    ijklmno
    jklmnop
    klmnopq
    lmnopqr
    mnopqrs
    Target 3
    nopqrst
    Target 4
    opqrstu
    pqrstuv
    qrstuvw
    rstuvwx
    stuvwxy
    tuvwxyz
    

    If you insist on using batch/CMD (and I sometimes do when nothing else is available), and you need to get the text on line #n (otherwise, head and tail would do just fine), you could produce a similar loop but replace the code from FINDSTR down to the end of the IF statement with something that compares _LINENO with some other variable, ECHO'ing the line if it is between the two values. I don't know if IF supports logical operators, so you may have to nest the IF statements, like

    IF !_LINENO! GEQ %START_LINE% IF !_LINENO! LEQ %END_LINE% @ECHO %%l