批处理命令可将一些信息添加到文件夹中的多个文件中

时间:2018-10-14 13:46:37

标签: batch-file

几天来我一直在寻找答案,但作为批处理命令的新手,却根本没有成功。

我的文件夹包含几个文本文件。我想添加几行都来自另一个文本文件的行。由于文本文件不遵循模式,因此我将使用行号。例如,

我的主要输入文本文件分别包含这些行。

This is explanation.
This one is another line.
That is a short content.

我想根据某些行(例如3,7和9,将以上这些行添加到我文件夹中的所有文本文件中,稍后可能会更改) 这是这些文件之一:

My file contains
Too many lines
This is a line
This one is another line
It goes on
Another sample
Another line
One more
Another more

分别从主输入文件中添加3、7、9之后

My file contains
Too many lines
This is explanation. <---- 3 goes here without deleting any line
This is a line
This one is another line
It goes on
Another sample
This one is another line. <---- 7 goes here
Another line
One more
That is a short content. <---- 9 goes here
Another more

我试图用Regex和Macro Record完成它。使用Notepad ++宏记录可能没问题。但是,我想用批处理文件来完成它。预先感谢。

1 个答案:

答案 0 :(得分:1)

我通常会忽略一些问题,这些问题并未显示出OP编写代码的任何努力。但是,在这种情况下我例外,因为解决方案涉及的概念不是那么简单(文件合并)。

@echo off
setlocal EnableDelayedExpansion

set "lines=3 7 9"

rem Initialize first line number to search
for /F "tokens=1*" %%i in ("%lines%") do (
   set "line=%%i"
   set "lines=%%j"
)

rem Redirect the input to *read* lines via SET /P command from input.txt file
< input.txt (

   rem Process the text file. Use FINDSTR /N command to numerate the lines in %%a
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" test.txt') do (

      if "%%a" equ "!line!" (

         rem Read next line from input.txt and output it
         set /P "nextLine="
         echo !nextLine!

         rem Get the next line number to search
         for /F "tokens=1*" %%i in ("!lines!") do (
            set "line=%%i"
            set "lines=%%j"
         )

      )

      rem Output the original line
      echo %%b
   )
)

test.txt:

My file contains
Too many lines
This is a line
This one is another line
It goes on
Another sample
Another line
One more
Another more

input.txt:

This is explanation.
This one is another line.
That is a short content.

输出:

My file contains
Too many lines
This is explanation.
This is a line
This one is another line
It goes on
Another sample
This one is another line.
Another line
One more
That is a short content.
Another more

此解决方案仅处理一个文本文件,因此您需要扩展该方法以处理多个文件。请注意,您必须对每个单独的文本文件重复整个过程 ...