我有一個測驗腳本如下:
# listingParser.ps1 --- by alphabetical order NOT numeric
$input_path = "C:\test\test3\Copy of 31832_226140__0001-00010.txt"
$output_file = "C:\test\test3\filterorder.txt"
$regexNum = '\d\d\d\s[A-Z][A-Z][A-Z]' # Roll Entry Number and NAME
$result = select-string -Path $input_path -Pattern $regexNum -CaseSensitive | % {
$_.Matches } | % { $_.Value }
$result | Sort-Object > $output_file
輸出如下所示:
001 BUZ
001 CAR
002 BUZ
003 BYE
005 BYE
007 CAR
008 BYF
009 BYF
010 CAR
011 BYG
012 CAR
014 CAR
017 BYT
018 BYT
021 CAD
問題是:
我的搜索每行文本只回傳一個實體。文本檔案的某些行包含搜索模式的多個示例,有些則不包含。好吧,至少這是我對結果的解釋(我剛剛再次檢查以確保)如何在檔案的任何行上指定所有示例?
我的要求是對
[A-Z][A-Z][A-Z]正則運算式的一部分進行排序。考慮到原始搜索需要字串的數字部分。
對于問題#2:此PowerShell:如何按列對文本檔案進行排序?描述拆分每個字串,在排序之前進行轉換。我合并了這個但得到了錯誤。最后,我對其進行了簡化(洗掉了演員表和排序方向)并使其正常作業。
$result | Sort-Object { $_.split()[-1] } > $output_file
所以我認為我已經對問題#2 進行了排序。
001 BUZ
002 BUZ
003 BYE
005 BYE
008 BYF
009 BYF
011 BYG
017 BYT
018 BYT
021 CAD
031 CAI
030 CAI
029 CAI
032 CAI
024 CAI
這樣就剩下如何回傳我的搜索的所有示例了。
任何建議,將不勝感激。
uj5u.com熱心網友回復:
我相信使用-AllMatchesonSelect-String應該可以解決每行查找所有匹配項的需要,另一種選擇可能是用于[regex]::Matches(..)查找匹配模式的所有外觀。
關于按字母順序對字符進行排序的需要,我個人會使用:
{ [regex]::Match($_, '[A-Z]{3}').Value }
如果您需要在將其與以下組合后按整數排序:
{ [int][regex]::Match($_, '\d{3}').Value }
您可以在下面看到這兩個示例,首先我們可以為您的檔案創建一個示例:
$dict = ([int][char]'A'..[int][char]'Z').ForEach([char])
function Ran {
'{0:000}' -f (Get-Random -Maximum 100)
$chars = 0..2 | ForEach-Object {
Get-Random -Maximum $dict.Count
}
[string]::new($dict[$chars])
}
$testCase = 0..10 | ForEach-Object {
[string]@(
if($_ % 2) { Ran }
Ran
)
}
現在,$testCase對我來說看起來像這樣:
089 CDO
088 XRQ 060 AXS
023 XMH
019 OFM 021 PYD
054 PDY
041 GCG 003 HCJ
071 MCG
033 NAP 089 NPN
011 CEG
069 GDP 011 YTM
025 WQH
接下來我們可以同時測驗Regex.Matches和Select-String:
$sortChar = { [regex]::Match($_, '[A-Z]{3}').Value }
$sortInt = { [int][regex]::Match($_, '\d{3}').Value }
$re = [regex]::Matches($testCase, '\d{3} [A-Z]{3}').Value |
Sort-Object $sortChar, $sortInt
$sls = ($testCase | Select-string -Pattern '\d{3} [A-Z]{3}' -CaseSensitive -AllMatches).Matches.Value |
Sort-Object $sortChar, $sortInt
最后,我們可以比較兩者是否給我們相同的(排序的)結果:
Compare-Object -ReferenceObject $re -DifferenceObject $sls -SyncWindow 0 -IncludeEqual
InputObject SideIndicator
----------- -------------
060 AXS ==
089 CDO ==
011 CEG ==
041 GCG ==
069 GDP ==
003 HCJ ==
071 MCG ==
033 NAP ==
089 NPN ==
019 OFM ==
054 PDY ==
021 PYD ==
025 WQH ==
023 XMH ==
088 XRQ ==
011 YTM ==
請注意,如果使用Regex.Matches替代方法,則在讀取檔案時應使用-Rawon Get-Content:
$content = Get-Content $input_path -Raw
[regex]::Matches($content, ...).Value | Sort-Object ... | Set-Content ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/437146.html
