Search code examples
filevariablesbatch-filesplitsequential

How to read xxx bytes from a file, output to variable(s)


Im trying to split a file into sequential pages that are 8159 bytes long. How can i read 8159 bytes of a file and save to the all!count! var? if the file is 8159 or less it reads the file and sets it to the !all! variable. How in the :split label can i read only so many bytes and save to variable.

@echo off
setlocal EnableDelayedExpansion EnableExtensions
for /f "tokens=*" %%a in ("newhtml.html") do set FileSize=%%~za
echo FileSize is %FileSize% bytes
if %FileSize% GTR 8159 goto split

SETLOCAL DisableDelayedExpansion 
set "all="
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ newhtml.html"`) do (
    set "line=%%a"
    SETLOCAL EnableDelayedExpansion
    set "line=!line:#=#S!"
    set "line=!line:*:=!"
    for /F "delims=" %%p in ("!all!#L!line!") do (
        ENDLOCAL
        set "all=%%p"
    )
)
SETLOCAL EnableDelayedExpansion
if defined all (
set "all=!all:~2!"
set ^"all=!all:#L=^
[blank line, remove this comment]
[blank line, remove this comment]   
!"
set "all=!all:#S=#!"
)
echo the all variable is: !all!
goto end

:split
set count=0
set /a all_sub=%FileSize% / 8159
set /a all_rem=%FileSize% %% 8159
if %all_rem% NEQ 0 set /a all_ttl=%all_sub% + 1
echo %all_sub% full page(s), %all_rem% bytes(s) leftover, %all_ttl% total pages

for  %%a in ("newhtml.html") do (
    set /a count=count + 1
    echo Read 8159 bytes from this file newhtml.html, save to all!count!
    if !count! EQU %all_ttl% echo All done & goto end
)

goto end

:end

the section that needs help is the split label, and in the for loop that reads the file, how to get only 8159 bytes of data at a a time and write to sequential variables. i guess that i should make the !all! a function and then call it?

edit: i found this file (http://www.fourmilab.ch/splits/) to do the splits, short work to add it to the ALL routine to reassemble. many thanks dbenham and jeb!


Solution

  • Why not simply read the file into an array?
    Each line would be one entry this works, if there isn't any line with more than ~8190 characters.
    Then you didn't need the replacing tricks for the linefeed and so on.

    But this depends of your actual problem.

    @echo off
    SETLOCAL DisableDelayedExpansion
    set "all="
    set count=0
    FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ aux1.txt"`) do (
        set "line=%%a"
        set /a count+=1
        SETLOCAL EnableDelayedExpansion
        set "line=!line:*:=!"
        for /F "delims=" %%p in (^"set "array[!count!]=!line!"^") do (
            ENDLOCAL
            %%p
        )
    )
    
    SETLOCAL EnableDelayedExpansion
    for /L %%n in (1 1 %count%) do (
      echo Line%%n:!array[%%n]!
    )