[英]How to combine multiple pattern searches and produce a single line output using $regex in PowerShell
提出的每個解決方案都假設有關個人的所有數據都存在於一行中。
由於Select-String中的每個 output 將是文件中每行的一個MatchInfo object,因此您只需連接每個 object 的Value
屬性值。
Select-String -Path $input_path -Pattern $regex -AllMatches |
Foreach-Object {$_.Matches.Value -join ","} > $output_file
所有這些都假設您的匹配順序在您的文件中是可預測的。 如果它們與該模式不同,那么這會變得稍微復雜一些。
如果您將正則表達式更改為使用命名捕獲組,則使用無序文件時您的結果可能更容易預測。 不過,您仍然需要在文件中維護字段格式。
$regex = '\b(?<ID>\d{8})\b|\b(?<Name>[A-Z][a-zA-Z]*\s[A-Z][a-zA-Z]*)\b|\b(?<Section>[A-Z]+\d{3})\b'
Select-String -Path t.txt -Pattern $regex -AllMatches |
Foreach-Object {
$groups = $_.Matches.Groups.where{$_.Success}
$ID = $groups.where{$_.Name -eq 'ID'}.Value
$Name = $groups.where{$_.Name -eq 'Name'}.Value
$Section = $groups.where{$_.Name -eq 'Section'}.Value
$ID,$Name,$Section -join ","
}
上面的代碼使用具有語法(?<captureName>)
的命名捕獲組。
另一種選擇是只使用帶有-Regex
和-File
參數的switch語句。 然后捕獲組甚至無關緊要,但每個正則表達式必須每行有一個匹配項。
$output = switch -Regex -File $input_File {
'\b\d{8}\b' {
$ID = $matches[0]
}
'\b[A-Z][a-zA-Z]*\s[A-Z][a-zA-Z]*\b' {
$Name = $matches[0]
}
'\b[A-Z]+\d{3}\b' {
$Section = $matches[0]
}
'$' {
$ID,$Name,$Section -join ","
}
}
$output > $output_file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.