powershell - 如何在 Powershell 中使用 Stream Writer 向文件中添加行
问题描述
我有 6GB 的插入语句 sql 文件,我想在每 150 行之后添加一个 GO 语句。该文件共有 9M 行。
我发现了一些使用 Powershell 脚本的代码,并且最推荐使用流或 .NET 命令来提高大文件的性能。
$reader = [System.IO.File]::OpenText("C:\src\customers1.sql")
$pathAndFilename = "c:\src\files\_customers_1.sql"
$streamout = new-object System.IO.StreamWriter $pathAndFilename
$batchSize = 150
$counter = 0
try {
for ( $line = $reader.ReadLine(); $line -ne $null; $line = $reader.ReadLine() )
{
$streamout.writeline($line)
$counter +=1
if ($counter -eq $batchsize)
{
$counter =0
$_ # send the current line to output
if ($_ -match ", NULL, NULL")
{
#Add Lines after the selected pattern
$line="GO"
$streamout.writeline($line)
}
}
}
}
finally {
$reader.Close()
$streamOut.close()
}
以上读取源文件并在 3 分钟内写入目标路径。但是,它不会在每 150 行代码之后编写 GO。似乎只是将文件复制过来。代码中有我遗漏的东西吗?
解决方案
推荐阅读
- java - ServerSocket 是真正的套接字吗?如果是,它的源 ip 和源端口是什么?
- ios - SwiftUI:为什么我的视图没有按照框架显示的那样显示在屏幕外?
- ssl - OPENSSL S_CLIENT 卡在 CONNECTED(00000003)
- angular - dgeni-packages:参数类型 (this | {})[] 不可分配给参数类型 PackageRef[] | 不明确的
- python - 我的 pygame 中的“敌人”与我的玩家具有相同的图像
- spring-integration - 如何在 Spring Integration 中从外部解析和获取 headers 属性值
- asp.net-core - 初始化用户管理器
在类库项目中 - html - 通过在 Django 中过滤数据库来显示用户
- reactjs - 除非发生整页刷新,否则 React Re-render Component 不起作用
- javascript - 关于 node.js 和 npm 库的可移植性