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?
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.
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.
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 .
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.
Something like this would probably work.
$sixArray = @()
$fourArray = @()
$file = Get-Content .\ThisFile.txt
$file | foreach {
if ($_.StartsWith("6"))
{
$sixArray += $_
}
elseif($_.StartsWith("4"))
{
$fourArray += $_
}
}
If you're running V4:
$fourArray,$sixArray =
((get-content $file) -match '^4|6').where({$_.startswith('4')},'Split')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With