powershell - 如何使用 PowerShell 拆分文本文件?

标签 powershell

我需要将一个大型 (500 MB) 文本文件(log4net 异常文件)拆分为可管理的 block ,例如 100 个 5 MB 文件就可以了。

我认为对于 PowerShell 来说这应该是在公园散步。我该怎么做?

最佳答案

关于一些现有答案的警告 - 对于非常大的文件,它们运行速度会非常慢。对于一个 1.6 GB 的日志文件,我在几个小时后就放弃了,因为我意识到在第二天我返回工作之前它无法完成。

两个问题:调用Add-Content打开、查找然后关闭源文件中每一行的当前目标文件。每次读取一点源文件并查找新行也会减慢速度,但我的猜测是 Add-Content 是罪魁祸首。

以下变体会产生稍微不太令人愉快的输出:它会在行中间分割文件,但它会在不到一分钟的时间内分割我的 1.6 GB 日志:

$from = "C:\temp\large_log.txt"
$rootName = "C:\temp\large_log_chunk"
$ext = "txt"
$upperBound = 100MB


$fromFile = [io.file]::OpenRead($from)
$buff = new-object byte[] $upperBound
$count = $idx = 0
try {
    do {
        "Reading $upperBound"
        $count = $fromFile.Read($buff, 0, $buff.Length)
        if ($count -gt 0) {
            $to = "{0}.{1}.{2}" -f ($rootName, $idx, $ext)
            $toFile = [io.file]::OpenWrite($to)
            try {
                "Writing $count to $to"
                $tofile.Write($buff, 0, $count)
            } finally {
                $tofile.Close()
            }
        }
        $idx ++
    } while ($count -gt 0)
}
finally {
    $fromFile.Close()
}

关于powershell - 如何使用 PowerShell 拆分文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1001776/

相关文章:

.net - xmlwriter writedoctype格式化

powershell - 复制项目,其中文件名是计算机主机名

powershell - Pester 模拟 CmdLets

sql - 为什么这个 powershell 脚本需要这么长时间?它使我的 GUI 崩溃

function - 函数将值返回到控制台,但不返回到文件

wpf - 如何在列表框中显示 Powershell 输出数组

c# - 自定义 PowerShell 管理单元 : custom format doesn't work

powershell - 使用多个psobject时,Get-Member不返回NoteProperty

powershell - 如何从Powershell输出中删除属性 namespace ?

xml - Powershell-如何在循环中获取多个XML属性