循环遍历文件 - 跳过长行

Loop through file - long line skipped

下面的loop/function 应该是编辑文件(只是替换文件中的第二行)。 原始文件包含一个 > 165000 符号的长行,执行此循环后,只有这一行在新文件中消失了。

setlocal EnableDelayedExpansion
set /a count=0
>"%~3" (
  for /f "usebackq delims=" %%A in ("%~2") do  (
    if !count!==1 (echo ^<html^>) else (
      setlocal DisableDelayedExpansion
      echo.%%A
      endlocal)
    set /a count+=1
  )
)
endlocal
goto:eof

我假设它与变量 (%%A) 可以存储的最大长度有关。.有没有办法避免这种行为?

提前致谢!

本机批处理不能处理超过 ~8191 字节的行,除非您采取一次读取一个字节的极端措施(它涉及创建一个长度 >= 源的虚拟文件,并使用 FC 派生字节) .这也是我很少使用批处理修改文件的众多原因之一。

我会用我的 JREPL.BAT utility:

call jrepl "^.*" "<html>" /jbegln "skip=(ln!=2)" /f "%~2" /o "%~3" 

但还有很多其他选择。

您可以使用 JScript 或 VBS 编写自定义代码,通过 CSCRIPT 执行。或者您可以使用 PowerShell。

或者您可以获得 sed 或 awk 的 Windows 端口,或者...


更新 - 可能的纯批处理解决方案

如果满足以下所有条件,则以下可能有效:

  • 你不关心制表符是否被转换成一串空格
  • 第一行长度 <= 1021 字节,并且没有尾随控制字符
  • 总行数<64k
  • (可能还有其他限制我想不起来了)
@echo off
setlocal enableDelayedExpansion
>"%~3" (
  set "ln="
  <"%~2" set /p "ln="
  echo(!ln!
  echo ^<html^>
  more +2 "%~2"
)

如果文件中的第一行和第二行小于 1 KB,那么下面的纯批处理文件应该可以解决您的问题:

@echo off
setlocal EnableDelayedExpansion

< "%~2" (

   rem Read the first line from redirected Stdin and copy it to Stdout
   set /P "line="
   echo !line!

   rem Read the second line and replace it by another one
   set /P "line="
   echo ^<html^>

   rem Copy the rest of lines to Stdout
   findstr "^"

) > "%~3"

有关此方法的更多说明,请参阅 this post; you may also see another example at