如何在变量行之后将一行添加到一系列文本文件中

时间:2016-11-01 17:24:10

标签: batch-file variables

我想在变量行之后的子文件夹中为一系列文本文件添加一行:

每个文本文件都命名为data.txt

我的文本文件包含以下行:

some text ...
[data.0 = fx_abc]
[data.1 = fx_xyz]
...
[data.n = fx_pqr]
... some text

每个文本文件都有不同的第n条数据线,

我想要添加的是第n行之后的第(n + 1)条数据行 在每个文本文件中:

[data.(n+1) = fx_some text]

我想使用批处理文件来执行此任务。

1 个答案:

答案 0 :(得分:0)

获取最后一个计数器,将其增加1并附加新行:

@ECHO OFF
SETLOCAL enabledelayedexpansion
REM for every textfile here and all subfolders...
for /r %%f in (data.txt) do (
  REM a default value if no match found:
  set "last=none"
  REM get last counter:
  for /f "tokens=2 delims=. " %%a in ('type "%%f"^|findstr /b /c:"[data."') do set "last=%%a"
  REM if not default value...
  if not "!last!" == "none" (
    REM increase counter:
    set /a last+=1 
    REM append line:
    echo [data.!last! = some_text]>>"%%f"
  ) 
)

编辑以匹配上次评论和已装帧的问题。无法插入文件,您必须重写整个文件。对于许多/大文件,这可能会有糟糕的表现。

@ECHO OFF
SETLOCAL enabledelayedexpansion
REM for every textfile here and all subfolders...
for /r %%f in (data.txt) do (
  REM a default value if no match found:
  set "last=none"
  REM get last counter:
  for /f "tokens=1,2,* delims=. " %%a in ('type "%%f"^|findstr /b /c:"[data."') do (
    set "last=%%b"
    set "line=%%a.%%b %%c"
    set /a new=last+1 
  ) 
  REM read file line by line and rewrite it:
  ( 
    for /f "usebackq delims=" %%a in ("%%f") do (
      echo %%a
      REM if that was the last "[data" line, add the new line: 
      if "%%a"=="!line!" echo [data.!new! = some_text]
    )
  )>"%%f.new"
  REM move the output file to the original name [/y = overwrite]
  move /y "%%f.new" "%%f" >nul
)