PowerShell获取大(大)文件的行数

Pra*_*nav 33 powershell line

从文件中获取行数的方法之一是PowerShell中的此方法:

PS C:\Users\Pranav\Desktop\PS_Test_Scripts> $a=Get-Content .\sub.ps1
PS C:\Users\Pranav\Desktop\PS_Test_Scripts> $a.count
34
PS C:\Users\Pranav\Desktop\PS_Test_Scripts> 
Run Code Online (Sandbox Code Playgroud)

但是,当我有一个800 MB的大文本文件时,如何在不读取整个文件的情况下从中获取行号?

上述方法将消耗太多RAM,导致脚本崩溃或完成时间过长.

Aki*_*kim 28

用于Get-Content -Read $nLinesAtTime逐个阅读您的文件:

$nlines = 0;

# Read file by 1000 lines at a time
gc $YOURFILE -read 1000 | % { $nlines += $_.Length };
[string]::Format("{0} has {1} lines", $YOURFILE, $nlines)
Run Code Online (Sandbox Code Playgroud)

这里有一个简单但速度慢的脚本来验证小文件的工作:

gc $YOURFILE | Measure-Object -Line
Run Code Online (Sandbox Code Playgroud)

  • 值得指出的是,您的第二种方法仅计算文本行。如果有空行,则不计算在内。 (4认同)

小智 23

这是我拼凑在一起的PowerShell脚本,它演示了一些计算文本文件中行的不同方法,以及每种方法所需的时间和内存.结果(如下)显示了时间和内存要求的明显差异.对于我的测试,使用ReadCount设置为100,看起来最佳点是Get-Content.其他测试需要更多的时间和/或内存使用.

#$testFile = 'C:\test_small.csv' # 245 lines, 150 KB
#$testFile = 'C:\test_medium.csv' # 95,365 lines, 104 MB
$testFile = 'C:\test_large.csv' # 285,776 lines, 308 MB

# Using ArrayList just because they are faster than Powershell arrays, for some operations with large arrays.
$results = New-Object System.Collections.ArrayList

function AddResult {
param( [string] $sMethod, [string] $iCount )
    $result = New-Object -TypeName PSObject -Property @{
        "Method" = $sMethod
        "Count" = $iCount
        "Elapsed Time" = ((Get-Date) - $dtStart)
        "Memory Total" = [System.Math]::Round((GetMemoryUsage)/1mb, 1)
        "Memory Delta" = [System.Math]::Round(((GetMemoryUsage) - $dMemStart)/1mb, 1)
    }
    [void]$results.Add($result)
    Write-Output "$sMethod : $count"
    [System.GC]::Collect()
}

function GetMemoryUsage {
    # return ((Get-Process -Id $pid).PrivateMemorySize)
    return ([System.GC]::GetTotalMemory($false))
}

# Get-Content -ReadCount 1
[System.GC]::Collect()
$dMemStart = GetMemoryUsage
$dtStart = Get-Date
$count = 0
Get-Content -Path $testFile -ReadCount 1 |% { $count++ }
AddResult "Get-Content -ReadCount 1" $count

# Get-Content -ReadCount 10,100,1000,0
# Note: ReadCount = 1 returns a string.  Any other value returns an array of strings.
# Thus, the Count property only applies when ReadCount is not 1.
@(10,100,1000,0) |% {
    $dMemStart = GetMemoryUsage
    $dtStart = Get-Date
    $count = 0
    Get-Content -Path $testFile -ReadCount $_ |% { $count += $_.Count }
    AddResult "Get-Content -ReadCount $_" $count
}

# Get-Content | Measure-Object
$dMemStart = GetMemoryUsage
$dtStart = Get-Date
$count = (Get-Content -Path $testFile -ReadCount 1 | Measure-Object -line).Lines
AddResult "Get-Content -ReadCount 1 | Measure-Object" $count

# Get-Content.Count
$dMemStart = GetMemoryUsage
$dtStart = Get-Date
$count = (Get-Content -Path $testFile -ReadCount 1).Count
AddResult "Get-Content.Count" $count

# StreamReader.ReadLine
$dMemStart = GetMemoryUsage
$dtStart = Get-Date
$count = 0
# Use this constructor to avoid file access errors, like Get-Content does.
$stream = New-Object -TypeName System.IO.FileStream(
    $testFile,
    [System.IO.FileMode]::Open,
    [System.IO.FileAccess]::Read,
    [System.IO.FileShare]::ReadWrite)
if ($stream) {
    $reader = New-Object IO.StreamReader $stream
    if ($reader) {
        while(-not ($reader.EndOfStream)) { [void]$reader.ReadLine(); $count++ }
        $reader.Close()
    }
    $stream.Close()
}

AddResult "StreamReader.ReadLine" $count

$results | Select Method, Count, "Elapsed Time", "Memory Total", "Memory Delta" | ft -auto | Write-Output
Run Code Online (Sandbox Code Playgroud)

以下是包含~95k行,104 MB的文本文件的结果:

Method                                    Count Elapsed Time     Memory Total Memory Delta
------                                    ----- ------------     ------------ ------------
Get-Content -ReadCount 1                  95365 00:00:11.1451841         45.8          0.2
Get-Content -ReadCount 10                 95365 00:00:02.9015023         47.3          1.7
Get-Content -ReadCount 100                95365 00:00:01.4522507         59.9         14.3
Get-Content -ReadCount 1000               95365 00:00:01.1539634         75.4         29.7
Get-Content -ReadCount 0                  95365 00:00:01.3888746          346        300.4
Get-Content -ReadCount 1 | Measure-Object 95365 00:00:08.6867159         46.2          0.6
Get-Content.Count                         95365 00:00:03.0574433        465.8        420.1
StreamReader.ReadLine                     95365 00:00:02.5740262         46.2          0.6
Run Code Online (Sandbox Code Playgroud)

以下是较大文件的结果(包含~285k行,308 MB):

Method                                    Count  Elapsed Time     Memory Total Memory Delta
------                                    -----  ------------     ------------ ------------
Get-Content -ReadCount 1                  285776 00:00:36.2280995         46.3          0.8
Get-Content -ReadCount 10                 285776 00:00:06.3486006         46.3          0.7
Get-Content -ReadCount 100                285776 00:00:03.1590055         55.1          9.5
Get-Content -ReadCount 1000               285776 00:00:02.8381262         88.1         42.4
Get-Content -ReadCount 0                  285776 00:00:29.4240734        894.5        848.8
Get-Content -ReadCount 1 | Measure-Object 285776 00:00:32.7905971         46.5          0.9
Get-Content.Count                         285776 00:00:28.4504388       1219.8       1174.2
StreamReader.ReadLine                     285776 00:00:20.4495721           46          0.4
Run Code Online (Sandbox Code Playgroud)


Hon*_*nza 14

这是一个基于Pseudothink的帖子的单行.

一个特定文件中的行:

"the_name_of_your_file.txt" |% {$n = $_; $c = 0; Get-Content -Path $_ -ReadCount 1000 |% { $c += $_.Count }; "$n; $c"}
Run Code Online (Sandbox Code Playgroud)

当前目录中的所有文件(单独):

Get-ChildItem "." |% {$n = $_; $c = 0; Get-Content -Path $_ -ReadCount 1000 |% { $c += $_.Count }; "$n; $c"}
Run Code Online (Sandbox Code Playgroud)

说明:

"the_name_of_your_file.txt"- >什么都不做,只提供后续步骤的文件名,需要双引号
|%- >别名ForEach-Object,迭代提供的项目(在这种情况下只有一个),接受管道内容作为输入,当前项目保存到$_
$n = $_- > $ n作为提供的文件的名称保存以供日后使用$_,实际上可能不需要
$c = 0 - >初始化$c为count
Get-Content -Path $_ -ReadCount 1000- >从提供的文件读取1000行(参见线程的其他答案)
|%- > foreach确实添加行数实际读到$c(将像1000 + 1000 + 123)
"$n; $c"- >一旦读完文件,打印文件名; 行数
Get-ChildItem "." - >只是向管道添加的项目多于单个文件名


lat*_*kin 12

首先要尝试的是一次流式传输Get-Content和构建一个行计数,而不是一次将所有行存储在一个数组中.我认为这将给出正确的流行为 - 即整个文件不会立即在内存中,只是当前行.

$lines = 0
Get-Content .\File.txt |%{ $lines++ }
Run Code Online (Sandbox Code Playgroud)

正如另一个答案所暗示的那样,添加-ReadCount可以加快速度.

如果这对你不起作用(太慢或太多记忆)你可以直接去StreamReader:

$count = 0
$reader = New-Object IO.StreamReader 'c:\logs\MyLog.txt'
while($reader.ReadLine() -ne $null){ $count++ }
$reader.Close()  # Don't forget to do this. Ideally put this in a try/finally block to make sure it happens.
Run Code Online (Sandbox Code Playgroud)


gre*_*aed 6

这是另一个使用.NET的解决方案:

[Linq.Enumerable]::Count([System.IO.File]::ReadLines("FileToCount.txt"))
Run Code Online (Sandbox Code Playgroud)

它不是很容易中断,但是在内存上却很容易。