Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 232
Grady D Avatar asked Apr 09 '14 15:04

Grady D


People also ask

How do I get the first letter of a string in PowerShell?

PowerShell Get First Character of StringUse the Substring method over the given string and pass the start index as 0 to the start point of the character and length as 1 to get a number of characters to return. The output of the above script gets the first character of a string.

How do I get characters from a string in PowerShell?

When you want to extract a part of a string in PowerShell we can use the Substring() method. This method allows us to specify the start and length of the substring that we want to extract from a string.

How do you check if a string contains a Substring in PowerShell?

If you want to know in PowerShell if a string contains a particular string or word then you will need to use the -like operator or the . contains() function. The contains operator can only be used on objects or arrays just like its syntactic counterpart -in and -notin .

How do I trim a string in PowerShell?

PowerShell Trim() methods (Trim(), TrimStart() and TrimEnd()) are used to remove the leading and trailing white spaces and the unwanted characters from the string or the raw data like CSV file, XML file, or a Text file that can be converted to the string and returns the new string.


2 Answers

Something like this would probably work.

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

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

    elseif($_.StartsWith("4"))
    {
        $fourArray += $_
    }
}
like image 150
notjustme Avatar answered Oct 20 '22 05:10

notjustme


If you're running V4:

$fourArray,$sixArray = 
((get-content $file) -match '^4|6').where({$_.startswith('4')},'Split')
like image 5
mjolinor Avatar answered Oct 20 '22 06:10

mjolinor