在PowerShell中逐行读取文件

我想在PowerShell中逐行读取一个文件。具体来说,我想在文件中进行循环,在循环中的一个变量中存储每一行,并对这一行进行一些处理。

我知道Bash的对应方法。

while read line do
    if [[ $line =~ $regex ]]; then
          # work here
    fi
done < file.txt

关于PowerShell循环的文档不多。

解决办法

关于PowerShell循环的文档不多。

PowerShell中关于循环的文档很多,你可能想看看以下帮助主题。about_For, about_ForEach, about_Do, [about_While] (https://docs.microsoft.com/en-gb/powershell/module/microsoft.powershell.core/about/about_while).

foreach($line in Get-Content .\file.txt) {
    if($line -match $regex){
        # Work here
    }
}

另一个解决你问题的习惯性PowerShell方法是将文本文件的行数输送到[ForEach-Object cmdlet](https://docs.microsoft.com/en-gb/powershell/module/Microsoft.PowerShell.Core/ForEach-Object)。

Get-Content .\file.txt | ForEach-Object {
    if($_ -match $regex){
        # Work here
    }
}

你可以通过Where-Object来过滤那些你感兴趣的行,而不是在循环中进行regex匹配。

Get-Content .\file.txt | Where-Object {$_ -match $regex} | ForEach-Object {
    # Work here
}
评论(3)

Get-Content的性能很差;它试图一次性将文件读入内存。

C# (.NET)文件阅读器逐一读取每一行的内容

最好的性能

foreach($line in [System.IO.File]::ReadLines("C:\path\to\file.txt"))
{
       $line
}

或性能稍差的

[System.IO.File]::ReadLines("C:\path\to\file.txt") | ForEach-Object {
       $_
}

foreach语句可能会比ForEach-Object稍快一些(更多信息见下面的评论)。

评论(12)

全能的开关在这里很有效。

'一
二
three' > 文件

$regex = '^t'

switch -regex -file file {
  $regex { "行是$_" }
}

输出。

行数为2 一行是三

评论(0)