繁体   English   中英

如何在 PowerShell 中使用带有正则表达式的条件语句?

[英]How to use a conditional statement with regex in PowerShell?

大约有十行数据。 对于每一行数据,我想指出该行是否包含数字。

如何为每一行打印出“是的,这一行有数字”或“不,这一行没有数字”,恰好一次?

输出:

thufir@dur:~/flwor/csv$ 
thufir@dur:~/flwor/csv$ pwsh import.ps1 
no digits

Name
----                                                                           
people…                                                                        

thufir@dur:~/flwor/csv$ 

代码:

$text = Get-Content -Raw ./people.csv
[array]::Reverse($text)

$tempAttributes = @()
$collectionOfPeople = @()

ForEach ($line in $text) { 
  if($line -notmatch '.*?[0-9].*?') {
    $tempAttributes += $line 
    Write-Host "matches digits"   
  }
  else {
    Write-Host "no digits"   
    $newPerson = [PSCustomObject]@{
      Name       = $line
      Attributes = $tempAttributes
    }
    $tempAttributes = @()
    $collectionOfPeople += $newPerson
  }
}

$collectionOfPeople

数据:

people
joe
phone1
phone2
phone3
sue
cell4
home5
alice
atrib6
x7
y9
z10

我打印“数字”或“无数字”的唯一原因是作为帮助构建对象的标记。

您可以使用以下内容:

switch -regex -file people.csv {
    '\d' { "yes" ; $_ }
    default { "no"; $_ }
}

\\d是匹配数字的正则表达式字符。 带有-regexswitch语句允许使用正则表达式来匹配文本。 当不满足其他条件时,将选择default条件。 $_是当前正在处理的行。

对于逐行处理, switch通常比Get-Content快。 由于您确实希望每行执行某些操作,因此您可能不想使用-Raw参数,因为它会将所有文件内容作为一个字符串读入。


# For Reverse Output
$output = switch -regex -file people.csv {
    '\d' { "yes" ; $_ }
    default { "no"; $_ }
}
$output[($output.GetUpperBound(0))..0)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM