簡體   English   中英

Powershell 計算文件中的行數

[英]Powershell Count lines in file

問題

Measure-Object -Line行為不一致,並且在嘗試讀取文件時不會返回正確的行數。

使用.Count似乎解決了這個特定問題,但它再次不一致,因為在處理字符串時它的工作方式不同。

如何始終如一地從文本或文件中獲取正確的行數?

移動電源

$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

@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM