首页 > 解决方案 > 批处理脚本在多个文件的第一行和第二行之间插入文本

问题描述

我正在尝试编写一个批处理脚本,在多个文件的第一行和第二行之间插入文本。该脚本接受一个文本文件作为输入,其中包括多个文件的路径。每个文件都在自己的行上。

file1.txt
file2.txt
file3.txt

对于我在尝试在第一行和第二行之间插入文本时读取的每个文件。

这就是我所拥有的。

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

Rem "loop through file names from input file"
for /F "tokens=1" %%a in (%1) do (

set source_file="%%a"

Rem Creates text file titled new.txt. 
copy NUL new.txt

set /a count = 0

Rem Loop intended to copy 1st line from source file to new, inserts new text on second line of new
Rem then copies the rest of the source file to new
for /F "tokens=1" %%a in (!source_file!) do (

   IF !count! == 0 (
       Rem copy first line of source code
       ECHO %%a >> new.txt
   )

   IF !count! == 1 (
       Rem insert my text here after 1st line
       ECHO text goes here >> new.txt
       
       Rem still need to copy line from file
       ECHO %%a >> new.txt
  )

  IF !count! gtr 1 (
      Rem copy line from source file. 
      ECHO %%a >> new.txt
  )
set /a count += 1
)

Rem Overwrite source file with new file
type new.txt > !source_file!

Rem delete disclaimer.txt
del new.txt

)

我覆盖的文件包含文件的名称而不是原始内容,并在第 1 行和第 2 行之间插入了新文本。

标签: windowsbatch-filecmd

解决方案


推荐阅读