Check first character of each line for a specific value in PowerShell

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-19 17:47:01

问题


I am reading in a text file that contains a specific format of numbers. I want to figure out if the first character of the line is a 6 or a 4 and store the entire line in an array for use later. So if the line starts with a six add the entire line into sixArray and if the line starts with a 4 add the entire line into fourArray.

How can I check the first character and then grab the remaining X characters on that line? Without replacing any of the data?


回答1:


Something like this would probably work.

$sixArray = @()
$fourArray = @()

$file = Get-Content .\ThisFile.txt
$file | foreach { 
    if ($_.StartsWith("6"))
    {
        $sixArray += $_
    }

    elseif($_.StartsWith("4"))
    {
        $fourArray += $_
    }
}



回答2:


If you're running V4:

$fourArray,$sixArray = 
((get-content $file) -match '^4|6').where({$_.startswith('4')},'Split')



回答3:


Use:

$Fours = @()
$Sixes = @()
GC $file|%{
    Switch($_){
        {$_.StartsWith("4")}{$Fours+=$_}
        {$_.StartsWith("6")}{$Sixes+=$_}
    }
}



回答4:


If it's me I'd just use a regex.

A pattern like this will catch everything you need.

`'^[4|6](?<Stuff>.*)$'`


来源:https://stackoverflow.com/questions/22967759/check-first-character-of-each-line-for-a-specific-value-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!