[英]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.
我想弄清楚该行的第一个字符是6还是4,并将整行存储在一个数组中以供日后使用。 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.
因此,如果行以6开头,则将整行添加到sixArray中,如果行以4开头,则将整行添加到fourArray中。
How can I check the first character and then grab the remaining X characters on that line? 如何检查第一个字符,然后获取该行的剩余X字符? Without replacing any of the data?
没有替换任何数据?
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: 如果您正在运行V4:
$fourArray,$sixArray =
((get-content $file) -match '^4|6').where({$_.startswith('4')},'Split')
Use: 采用:
$Fours = @()
$Sixes = @()
GC $file|%{
Switch($_){
{$_.StartsWith("4")}{$Fours+=$_}
{$_.StartsWith("6")}{$Sixes+=$_}
}
}
If it's me I'd just use a regex. 如果是我,我只是使用正则表达式。
A pattern like this will catch everything you need. 像这样的模式将抓住你需要的一切。
`'^[4|6](?<Stuff>.*)$'`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.