Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read a file from line x to line y (dos/win batch file)

I have a series of log files.

I parse these log files with findstr to determine the first instance of a string of text, then return the file name and the line lumber the match was found on as variables.

I then use findstr to parse the file the match was found in for another text string. I return the matching line number as a variable.

I now have the file, the starting and ending line numbers.

I need to return the block of text between my line numbers.

All output is redirected to a textfile represented by the variable casenotes

Here is my code:

:test
echo:            >> %casenotes%
echo:   test         >> %casenotes%
for /f "tokens=1,2* delims=:" %%a in ('findstr /N /C:"Optimize ThreadPools" *_MAGT_*.txt') do set startline=%%b & set filefoundin=%%a & goto part2
:part2
for /f "tokens=1,2* delims=:" %%a in ('findstr /N /C:"After optimization" %filefoundin%') do set endline=%%a & goto part3
:part3
echo:                       >> %casenotes%
echo: filefound in: %filefoundin%       >> %casenotes%
echo: startline is: %startline%     >> %casenotes%
echo: endline is:   %endline%       >> %casenotes%
echo:                       >> %casenotes%
     echo: now do something magic to read everything between lines %startline% and %endline% from %filefoundin% and redirect that output to %casenotes%

Any advice appreciated!

like image 699
user1851547 Avatar asked Nov 25 '12 18:11

user1851547


People also ask

How do I read a text file line by line in a batch file?

Reading of files in a Batch Script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read. Since there is a no direct command to read text from a file into a variable, the 'for' loop needs to be used to serve this purpose.

How do I read the contents of a batch file?

Using a BAT file in Windows is as simple as double-clicking or double-tapping it. You don't need to download any special program or tool. To use the first example from above, entering that text into a text file with a text editor and then saving the file with the .

How do you go to the next line in CMD?

The Windows command prompt (cmd.exe) allows the ^ (Shift + 6) character to be used to indicate line continuation. It can be used both from the normal command prompt (which will actually prompt the user for more input if used) and within a batch file.

What is %% f in batch file?

%%parameter A replaceable parameter: in a batch file use %%G (on the command line %G) FOR /F processing of a text file consists of reading the file, one line of text at a time and then breaking the line up into individual items of data called 'tokens'.


2 Answers

try this: @echo off

set file_to_read=read.txt
set /a start_line=1
set /a end_line=6
set outfile=outfile
set counter=1

break > %outfile%
setlocal ENABLEDELAYEDEXPANSION


for /f "delims=*" %%A  in (%file_to_read%) do (
    if !counter! GEQ !start_line! (
        echo %%A
        echo %%A >> !outfile!
    )
    set /A counter=!counter!+1

    if !counter! GEQ !end_line! (
        goto :endLoop
    )
)
:endLoop

This will no count empty lines.

like image 154
npocmaka Avatar answered Oct 28 '22 23:10

npocmaka


@Echo OFF

Set "File=Test.txt"
Set /A "Start_Line=3"
Set /A "End_Line=6"

For /F "Tokens=*" %%# In ('Type "%FILE%"') DO (
    Call Set /A "Line+=1"
    CMD /C "IF %%LINE%% GEQ %Start_Line% IF %%LINE%% LEQ %END_Line% (Echo %%#>>"Output.txt")"
)

Pause&Exit

UPDATE

Another way with same accuracy

@Echo OFF

Set    "File=Test.txt"
Set /A "Start_Line=3"
Set /A "End_Line=6"

For /F "Tokens=* delims=" %%# In ('Type "%FILE%"') DO (
    Set /A "Line+=1"
    CALL :READ_LINES "%%#"
)

:READ_LINES
(IF %LINE% GEQ %Start_Line% IF %LINE% LEQ %END_Line% (Echo %*>>"Output.txt") ELSE (GOTO:END)) & GOTO:EOF

:END
Pause&Exit

for any other type of text manipulation you can use my TEXTMAN subroutine the next time (Commentlines in spanish, sorry):

    @Echo OFF

:: TEXT MANIPULATOR ROUTINE v0.1 
:: by Elektro H@cker

USO:
:TEXTMAN [ACCIÓN] [LÍNEA] [ARCHIVO] [TEXTO (Opcional)]


REM ACCIONES:
REM 
REM  AL  = ADD_LEFT           * AÑADIR TEXTO AL PRINCIPIO DE UNA LÍNEA
REM  AR  = ADD_RIGHT          * AÑADIR TEXTO AL FINAL DE UNA LÍNEA
REM  E   = ERASE              * ELIMINAR UNA LÍNEA
REM  I   = INSERT             * INSERTAR UNA LÍNEA (VACÍA O CON TEXTO)
REM  RL  = REPLACE_LINE       * REEMPLAZAR UNA LÍNEA
REM  RS  = REPLACE_STRING     * REEMPLAZAR PALABRAS DE UNA LÍNEA
REM  RSA = REPLACE_STRING_ALL * REEMPLAZAR PALABRAS EN TODAS LAS LÍNEAS
REM  C+  = CHARACTER_PLUS     * ELIMINAR LOS PRIMEROS "X" CARACTERES EN TODAS LAS LÍNEAS
REM  C-  = CHARACTER_LESS     * ELIMINAR LOS ÚLTIMOS  "X" CARACTERES EN TODAS LAS LÍNEAS
REM  L+  = LINE_PLUS          * CORTAR LAS PRIMERAS "X" LÍNEAS
REM  L-  = LINE_LESS          * CORTAR LAS ÚLTIMAS  "X" LÍNEAS


REM EJEMPLOS DE USO:

:: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: ::
::
:: Elimina la línea 3
:: Call :TEXTMAN E 3 "Test.txt"
::
:: Añade una frase al principio de la línea 3
:: Call :TEXTMAN AL 3 "Test.txt" "Elektro H@cker"
::
:: Añade una frase al final de la línea 3
:: Call :TEXTMAN AR 3 "Test.txt" "Elektro H@cker"
::
:: Inserta una línea vacía en la línea 3
:: Call :TEXTMAN I 3 "Test.txt"
::
:: Inserta una línea con texto en la línea 3
:: Call :TEXTMAN I 3 "Test.txt" "Elektro H@cker"
::
:: Reemplaza la línea 3 por completo
:: Call :TEXTMAN RL 3 "Test.txt" "Elektro H@cker"
::
:: Reemplaza las palabras "Elektro" por "H@cker" en la línea 3
:: Call :TEXTMAN RS 3 "Test.txt" "Elektro" "H@cker"
::
:: Reemplaza las palabras "Elektro" por "H@cker" en todas las líneas
:: Call :TEXTMAN RSA "Test.txt" "Elektro" "H@cker"
::
:: Elimina los 3 primeros caracteres de todas las líneas
:: Call :TEXTMAN C+ 3 "Test.txt"
::
:: Elimina los 3 uúltimos caracteres de todas las líneas
:: Call :TEXTMAN C- 3 "Test.txt"
::
:: Elimina las 3 primeras líneas
:: Call :TEXTMAN L+ 3 "Test.txt"
::
:: Elimina las 3 últimas líneas
:: Call :TEXTMAN L- 3 "Test.txt"
::
:: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: :: ::

PAUSE&EXIT

:TEXTMAN
(SET /A "A=0", "LINE=0", "TOTAL_LINES=0")  &  (CALL :%~1 %* || (ECHO Parametro incorrecto & Exit /B 1)) & (GOTO:EOF)
:AL
(For /F "usebackq tokens=*" %%@ in ("%~3") DO (Call Set /A "LINE+=1" && (CMD /C "IF NOT "%%LINE%%" EQU "%~2" (Echo %%@ >> "%~nx3.NEW") ELSE (Echo %~4%%@ >> "%~nx3.NEW")"))) && (CALL :RENAMER "%~3") & (GOTO:EOF)
:AR
(For /F "usebackq tokens=*" %%@ in ("%~3") DO (Call Set /A "LINE+=1" && (CMD /C "IF NOT "%%LINE%%" EQU "%~2" (Echo %%@ >> "%~nx3.NEW") ELSE (Echo %%@%~4 >> "%~nx3.NEW")"))) && (CALL :RENAMER "%~3") & (GOTO:EOF)
:E
(For /F "usebackq tokens=*" %%@ in ("%~3") DO (Call Set /A "LINE+=1" && (CMD /C "IF NOT "%%LINE%%" EQU "%~2" (Echo %%@ >> "%~nx3.NEW")"))) && (CALL :RENAMER "%~3") & (GOTO:EOF)
:I
(For /F "usebackq tokens=*" %%@ in ("%~3") DO (Call Set /A "LINE+=1" && (CMD /C "IF     "%%LINE%%" EQU "%~2" (IF NOT "%~4" EQU "" (Echo %~4 >> "%~nx3.NEW") ELSE (Echo. >> "%~nx3.NEW"))" & Echo %%@ >> "%~nx3.NEW"))) && (CALL :RENAMER "%~3") & (GOTO:EOF)
:RL
(For /F "usebackq tokens=*" %%@ in ("%~3") DO (Call Set /A "LINE+=1" && (CMD /C "IF NOT "%%LINE%%" EQU "%~2" (Echo %%@ >> "%~nx3.NEW") ELSE (Echo %~4 >> "%~nx3.NEW")"))) && (CALL :RENAMER "%~3") & (GOTO:EOF)
:RS
(For /F "usebackq tokens=*" %%@ in ("%~3") DO (Call Set /A "LINE+=1" && (CMD /C "IF NOT "%%LINE%%" EQU "%~2" (Echo %%@ >> "%~nx3.NEW") ELSE (CALL SET "STRING=%%@" && CALL ECHO %%STRING:%~4=%~5%% >> "%~nx3.NEW")"))) && (CALL :RENAMER "%~3") & (GOTO:EOF)
:RSA
(For /F "usebackq tokens=*" %%@ in ("%~2") DO (CALL SET "STRING=%%@" && (CALL ECHO %%STRING:%~3=%~4%% >> "%~2.NEW"))) && (CALL :RENAMER "%~2") & (GOTO:EOF)
:C+
(For /F "usebackq tokens=*" %%@ in ("%~3") DO (Call Set   "LINE=%%@" && (CALL ECHO %%LINE:~%~2%% >>    "%~nx3.NEW"))) && (CALL :RENAMER "%~3") & (GOTO:EOF)
:C-
(For /F "usebackq tokens=*" %%@ in ("%~3") DO (Call Set   "LINE=%%@" && (CALL ECHO %%LINE:~0,-%~2%% >> "%~nx3.NEW"))) && (CALL :RENAMER "%~3") & (GOTO:EOF)
:L+
(Call SET /A "A=%~2-1") && (Call TYPE "%~3" | @MORE +%%A%% > "%~nx3.NEW") && (CALL :RENAMER "%~3") & (GOTO:EOF)
:L-
(FOR /F %%X IN ('TYPE "%~3"') DO (CALL SET /A "TOTAL_LINES+=1")) & (CALL SET /A "TOTAL_LINES-=%~2-1") & (For /F "usebackq tokens=*" %%@ in ("%~3") DO (Call Set /A "LINE+=1" & Call echo " %%LINE%%!!| FINDSTR " %%TOTAL_LINES%% " && CALL :RENAMER "%~3" && GOTO:EOF || (Echo %%@ >> "%~nx3.NEW")))
:RENAMER
(REN "%~1" "%~nx1.BAK") & (MOVE /Y "%~nx1.BAK" "%TEMP%\" >NUL) & (REN "%~nx1.NEW" "%~nx1") & (GOTO:EOF)
like image 32
ElektroStudios Avatar answered Oct 28 '22 23:10

ElektroStudios