简体   繁体   English

在PowerShell中检查每行的第一个字符是否有特定值

[英]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.

相关问题 从文件的每一行中删除第一个字符时出现 Powershell 错误 - Powershell error during removal of first character from each line of a file PowerShell-如果有特定字符,则删除第一个字符 - PowerShell - remove first character if a specific character 如何在PowerShell中的第一个特殊字符实例后删除数组中每行中的剩余文本 - How to remove remaining text in each line in an array after first instance of special character in PowerShell 如果行以特定字符开头,则 powershell 替换命令 - powershell replace command if line starts with a specific character Powershell - 替换文件中每行的前 3 个字符 - Powershell - Replacing first 3 characters of each line in file 使用.Replace()处理文件中每行的第一个字符 - Manipulating first character of each line in a file with .Replace() 替换文件中每行的第一个和最后一个字符 - Replace first and last character of each line in file 检查文件的前 n 个字节是否特定于 Powershell - Check if the first n bytes of a file are specific in Powershell 如何使用PowerShell在某些字符上为每一行添加内容 - how to add content for each line on certain character with powershell 是否有一个PowerShell Get-Content函数可根据第一个字符提取行? - Is there a PowerShell Get-Content Function to extract line based on the first character?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM