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

前端 未结 4 1249
野的像风
野的像风 2021-01-18 03:42

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

相关标签:
4条回答
  • 2021-01-18 04:06

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

    A pattern like this will catch everything you need.

    `'^[4|6](?<Stuff>.*)$'`
    
    0 讨论(0)
  • 2021-01-18 04:12

    Something like this would probably work.

    $sixArray = @()
    $fourArray = @()
    
    $file = Get-Content .\ThisFile.txt
    $file | foreach { 
        if ($_.StartsWith("6"))
        {
            $sixArray += $_
        }
    
        elseif($_.StartsWith("4"))
        {
            $fourArray += $_
        }
    }
    
    0 讨论(0)
  • 2021-01-18 04:21

    If you're running V4:

    $fourArray,$sixArray = 
    ((get-content $file) -match '^4|6').where({$_.startswith('4')},'Split')
    
    0 讨论(0)
  • 2021-01-18 04:28

    Use:

    $Fours = @()
    $Sixes = @()
    GC $file|%{
        Switch($_){
            {$_.StartsWith("4")}{$Fours+=$_}
            {$_.StartsWith("6")}{$Sixes+=$_}
        }
    }
    
    0 讨论(0)
提交回复
热议问题