Powershell计数文件中的行

时间:2018-08-31 15:57:03

标签: string file powershell

问题

Measure-Object -Line的行为不一致,并且在尝试读取文件时未返回正确的行数。

使用.Count似乎可以解决此特定问题,但又不一致,因为在处理字符串时,它的工作方式不同。

问题

如何始终从文本或文件中获取正确的行数?

MWE

$File       = ".\test.ini"
$FileContent  = Get-Content $File
$Content =
"    # 1
    [2]
    3

    5

    [7]

    ; 9
"

$EndOfFile    = $FileContent | Measure-Object -Line
$EndOfText    = $Content | Measure-Object -Line

Write-Output "Lines from file: $($EndOfFile.Lines)"
Write-Output "Lines from text: $($EndOfText.Lines)"
Write-Output "Count from file: $($FileContent.Count)"
Write-Output "Count from text: $($Content.Count)"

注意test.ini的内容与$Content变量完全相同。

输出

Lines from file: 6
Lines from text: 9
Count from file: 9
Count from text: 1

1 个答案:

答案 0 :(得分:1)

@ TheIncorrigible1的意思是真的。要在您的示例中做到一致,您必须采用以下方式:

$File       = ".\test.ini"
$FileContent  = Get-Content $File

$Content = @(
    "# 1",
    "[2]",
    "3",
    "",
    "5",
    ""
    "[7]",
    ""
    "; 9"
)

$EndOfFile    = $FileContent | Measure-Object -Line
$EndOfText    = $Content | Measure-Object -Line

Write-Output "Lines from file: $($EndOfFile.Lines)"
Write-Output "Lines from text: $($EndOfText.Lines)"
Write-Output "Count from file: $($FileContent.Count)"
Write-Output "Count from text: $($Content.Count)"

一致的输出:

Lines from file: 6
Lines from text: 6
Count from file: 9
Count from text: 9