PowerShell获取大(大)文件的行数 [英] PowerShell get number of lines of big (large) file

查看:600
本文介绍了PowerShell获取大(大)文件的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

One of the ways to get number of lines from a file is this method in 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> 

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

However, when I have a large 800 MB text file, how do I get the line number from it without reading the whole file?

以上方法将消耗过多的RAM,从而导致脚本崩溃或花费太长时间才能完成.

The above method will consume too much RAM resulting in crashing the script or taking too long to complete.

推荐答案

使用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)

这是简单但缓慢的脚本,用于验证小文件上的工作:

And here is simple, but slow script to validate work on a small file:

gc $YOURFILE | Measure-Object -Line

这篇关于PowerShell获取大(大)文件的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆