在PowerShell中逐行读取文件 [英] Read file line by line in PowerShell

查看:149
本文介绍了在PowerShell中逐行读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to read a file line by line in PowerShell. Specifically, I want to loop through the file, store each line in a variable in the loop, and do some processing on the line.

我知道 Bash 等价物:

I know the Bash equivalent:

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

关于 PowerShell 循环的文档不多.

Not much documentation on PowerShell loops.

推荐答案

关于 PowerShell 循环的文档不多.

Not much documentation on PowerShell loops.

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

Documentation on loops in PowerShell is plentiful, and you might want to check out the following help topics: about_For, about_ForEach, about_Do, about_While.

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

解决您的问题的另一个惯用 PowerShell 解决方案是将文本文件的行通过管道传输到 ForEach-Object cmdlet:

Another idiomatic PowerShell solution to your problem is to pipe the lines of the text file to the ForEach-Object cmdlet:

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

<小时>

您可以通过 Where-Object 只过滤你感兴趣的那些:


Instead of regex matching inside the loop, you could pipe the lines through Where-Object to filter just those you're interested in:

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

这篇关于在PowerShell中逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆