Check first character of each line for a specific value in PowerShell
Solution 1
Something like this would probably work.
$sixArray = @()
$fourArray = @()
$file = Get-Content .\ThisFile.txt
$file | foreach {
if ($_.StartsWith("6"))
{
$sixArray += $_
}
elseif($_.StartsWith("4"))
{
$fourArray += $_
}
}
Solution 2
If you're running V4:
$fourArray,$sixArray =
((get-content $file) -match '^4|6').where({$_.startswith('4')},'Split')
Solution 3
Use:
$Fours = @()
$Sixes = @()
GC $file|%{
Switch($_){
{$_.StartsWith("4")}{$Fours+=$_}
{$_.StartsWith("6")}{$Sixes+=$_}
}
}
Grady D
Currently going to school for computer science work as an Information Systems engineer. Have been involved with technology for many years. Love Android, java, c++ and python. Main focus is web development and writing scripts to improve employee production. Love to learn about network security and network defense, pentesting. Primary languages are HTML5/CSS3, Python, Powershell and Java. Primary applications/programs are SharePoint and Salesforce
Updated on July 23, 2022Comments
-
Grady D almost 2 years
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?