我有一個包含要修改的字串的文本檔案。
示例文本檔案內容:
abc=1
def=2
ghi=3
如果我運行此代碼:
$file = "c:\test.txt"
$MinX = 100
$MinY = 100
$a = (Get-Content $file) | %{
if($_ -match "def=(\d*)"){
if($Matches[1] -gt $MinX){$_ -replace "$($Matches[1])","$($MinX)" }
}
}
$a
結果是:
def=100
如果我像這樣省略大于號檢查:
$a = (Get-Content $file) | %{
if($_ -match "def=(\d*)"){
$_ -replace "$($Matches[1])","$($MinX)"
}
}
$a
結果是正確的:
abc=1
def=100
ghi=3
我不明白在進行替換之前進行簡單的整數比較是如何把事情搞砸的如此嚴重,誰能告訴我我遺漏了什么?
uj5u.com熱心網友回復:
那是因為運算式($Matches[1] -gt $MinX)是一個字串比較。在 Powershell 中,比較的左側指示比較型別,因為它是 type [string],Powershell 必須將運算式的右側強制轉換/轉換為[string]也。因此,您的運算式被評估為([string]$Matches[1] -gt [string]$MinX)。
uj5u.com熱心網友回復:
比較運算子-gt永遠不會為您提供 $true 的值,因為您需要
- 首先將 $matches[1]字串值轉換為 int,以便比較兩個整數
2永遠不會大于100.. 將運算子更改為-lt。- 您的代碼只輸出一行,因為您忘記還輸出與正則運算式不匹配的未更改行
$file = 'c:\test.txt'
$MinX = 100
$MinY = 100
$a = (Get-Content $file) | ForEach-Object {
if ($_ -match '^def=(\d )'){
if([int]$matches[1] -lt $MinX){ $_ -replace $matches[1],$MinX }
}
else {
$_
}
}
$a
或者使用switch(也比使用 Get-Content 更快):
$file = 'c:\test.txt'
$MinX = 100
$MinY = 100
$a = switch -Regex -File $file {
'^def=(\d )' {
if([int]$matches[1] -lt $MinX){ $_ -replace $matches[1],$MinX }
}
default { $_ }
}
$a
輸出:
abc=1
def=100
ghi=3
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/380568.html
