batch-fileauto-updatechatroom

Batch .txt reader


So, basically I want a Batch file to read a .txt. The problem is that the Batch file needs to update everytime a new line gets written to the .txt

@echo off
set "pc=%1"
FOR /F "delims=:" %%A IN ('findstr /N .* "%pc%"') DO set "zeilen=%%A" 
type %pc%
set /A zeilen1=%zeilen%
:loop
if not %zeilen% == %zeilen1% (
set "line="
set zeilen2=%zeilen% - 1
for /f %%a in ('more/e +%zeilen2% ^< %pc%') do (
   if not defined line set "line=%%a"
)
 echo %line%   
 set /A zeilen+=1
)
FOR /F "delims=:" %%A IN ('findstr /N .* "%pc%"') DO set "zeilen1=%%A
goto loop

I also can't use the type command (line 9-13) because I don't want to refresh the whole .txt only the last line.

sry for my poor english

Thanks

To start the Batch you need to do something like this call batch.cmd txtname.txt


Solution

  • If you don't wish to use third party options and wish to keep it pure batch, it is very possible. From your question, it sounds like you wish to read the last line of a text file and have it update that text each time the text file is edited. Further more, this batch file much be call'ed to when it needs to be used.

    To do this, we can compare the date it was last modified using forfiles in an for loop. The reason for this is that if we use the file properties EX: ECHO Last-Modified Date : %%~ta we will not get the properties down to seconds. Thus the file will only compare down to the minutes.

    Now that we can grab the last modified properties we can use an IF statement to look for when the file get a new time stamp. From there we can use a modified script that reads only the last line of a text file (Configurable by set /a LINES=LINES+1 LINES+1 - Infin) made by @Patrick Cuff

    To call this batch file you will want to use call ReadFile.bat txtname.txt

    Bellow is the full script.

    ReadFile.bat

    @ECHO OFF
    @GOTO READ
    
    :LOOP
    Rem | Look for changes
    FOR /f %%a in ('forfiles /M %1 /C "cmd /c echo @fdate-@ftime"') DO (set FileTimeCurrent=%%a)
    
    IF "%FileTimeLoad%"=="%FileTimeCurrent%" (goto LOOP) else (goto READ)
    
    :READ
    cls
    
    Rem | Get current date
    FOR /f %%a in ('forfiles /M %1 /C "cmd /c echo @fdate-@ftime"') DO (set FileTimeLoad=%%a)
    
    Rem | Get the number of lines in the file
    set LINES=0
    for /f "delims==" %%I in (%1) do (
        set /a LINES=LINES+1
    )
    
    Rem | Print the last line
    set /a LINES=LINES-1
    more +%LINES% < %1
    
    goto LOOP
    

    For help on any of the commands do the following: