如何在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)]

最新更新