在其他文件开头的 n 行和 3 行之后插入带有文本的新行 - Windows

Insert new line with text after n lines and 3 lines at beginning from other file - Windows


能否请您帮忙找到一个Windows解决方案来解决以下需求?

目前我在 Notepad++ 中使用正则表达式手动执行此操作,但此例程将由多个人使用,自动方式会更好。

我有一个巨大的文本文件,其中包含将加载到 SQL 服务器中的插入语句。
我想做的是:
1 - 插入开始交易;在文件的开头
2 - 插入 COMMIT TRANSACTION;在文件末尾
3 - 每 1000 行后插入 3 行文本:
提交交易;

开始交易;
4 - 将前 3 行从另一个文件复制到当前文件

这件事会发生在动态路径

这是一个包含 5000 行的文件的示例:

输入

Line_No 文字
1 插入...
500 插入...
1000 插入...
1001 插入...
2000 插入...
2001 插入...
5000 插入...

期望输出

Line_No 文字
第一行来自同一路径中其他文件的文本
第二行来自同一路径中其他文件的文本
第 3 行来自同一路径中其他文件的文本
开始交易;
1 插入...
500 插入...
1000 插入...
1001 提交交易;
1002 开始
1003 开始​​交易;
1004 插入...
2000 插入...
2001 年提交交易;
2002 去
2003 开始​​交易;
2004 插入...
5000 插入...
5001 提交交易;

太感谢了! :)

更新: 这是使用@mjolinor 提供的解决方案完成此任务的解决方案:

$cd = Get-Location
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
$newfile = "$cd\newfile.sql"
$oldfile = "$cd\oldfile.sql"
$string = Get-Content $cd\otherfile.txt

$header = @"
:out $PSScriptRoot\log.txt
USE $string
GO
BEGIN TRANSACTION; 
"@

$insert = @'
COMMIT TRANSACTION; 
GO
BEGIN TRANSACTION; 
'@

$header | Set-Content $newfile
 Get-Content $oldfile -ReadCount 1000 |
   ForEach-Object { $_,$insert | Add-Content $newfile -Force}
 'COMMIT TRANSACTION;' | Add-Content $newfile

谢谢@mjolinor :-)!

没有广泛测试,但我认为这应该有效:

$newfile = 'c:\somedir\newfilename.txt'
$oldfile = 'c:\somedir\oldfilename.txt'
$otherfile = 'c:\somedir\someotherfilename.txt'

$insert = @'
COMMIT TRANSACTION; 
GO
BEGIN TRANSACTION; 
'@

'BEGIN TRANSACTION' | Set-Content $newfile
 Get-Content $oldfile -ReadCount 1000 |
   ForEach-Object { $_,$insert | Add-Content $newfile }
 Get-Content $otherfile -Head 3 | Add-Content $newfile