如何从文件读取xxx字节,输出到变量

时间:2012-05-17 15:33:57

标签: file variables batch-file split sequential

我试图将文件拆分为8159字节长的连续页面。我怎么能读取8159字节的文件并保存到全部!计数! VAR?如果文件是8159或更少,它会读取文件并将其设置为!all!变量。如何在:split标签中只读取这么多字节并保存到变量。

@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

需要帮助的部分是split标签,而在读取文件的for循环中,如何一次只获取8159个字节的数据并写入顺序变量。我想我应该做的!全部!一个函数,然后调用它?

编辑:我发现这个文件(http://www.fourmilab.ch/splits/)做了拆分,简短的工作就是把它添加到ALL例程重新组装。非常感谢dbenham和jeb!

1 个答案:

答案 0 :(得分:2)

为什么不简单地将文件读入数组? 如果没有任何超过~8190个字符的行,则每行将是一个有效的条目 然后你不需要为换行等替换技巧等等。

但这取决于你的实际问题。

@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]!
)