在PowerShell中逐行读取文件

问题描述 投票:61回答:2

我想在PowerShell中逐行读取文件。具体来说,我想循环遍历文件,将每一行存储在循环中的变量中,并在该行上进行一些处理。

我知道Bash的等价物:

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

关于PowerShell循环的文档不多。

powershell powershell-ise
2个回答
129
投票

关于PowerShell循环的文档不多。

PowerShell中有关循环的文档很多,您可能需要查看以下帮助主题:about_Forabout_ForEachabout_Doabout_While

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

另一个惯用的PowerShell解决方案是将文本文件的行传递给ForEach-Object cmdlet

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

而不是在循环内部进行正则表达式匹配,您可以通过Where-Object管道线来过滤您感兴趣的那些:

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

40
投票

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略快(请参阅下面的评论以获取更多信息)。


0
投票

万能开关在这里工作得很好:

'one
two
three' > file

$regex = '^t'

switch -regex -file file { 
  $regex { "line is $_" } 
}

输出:

line is two
line is three
© www.soinside.com 2019 - 2024. All rights reserved.