gpt4 book ai didi

string - Powershell计数文件中的行

转载 作者:行者123 更新时间:2023-12-02 23:53:25 24 4
gpt4 key购买 nike

问题
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

最佳答案

的确,@ 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

关于string - Powershell计数文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52119081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com