2016-12-01 93 views
0

使用Powershell version 3 &讀取文件的內容,然後我需要查看該文件中是否包含幾個字符串中的一個,如果是,則將其替換。在我的情況下,問題是我需要匹配的字符串之一可能會有不同數量的空格(或根本沒有)。Powershell - 匹配可能包含空格的字符串

我匹配的字符串中有雙引號,後面跟冒號(:),然後是空格(或無),然後是任意數量的狀態(可以是字母或數字),後跟逗號。爲了簡單起見,我只是在下面的代碼中使用了一個數字。

$txt = (Get-Content $file) 
$oldstr = "`"status`": 1," 
$newstr = '`"status`": 0," 
if (($txt.Contains($old1)) -or ($txt.Contains($oldstr)) -or ($txt.Contains($old2))) { 
    $txt.Replace($oldstr, $newstr).Replace($old1, $new1).replace($old2, $new2)| Set-Content -Path $file 
} 

我在被匹配$oldstr可具有的問題沒有,結腸和狀態碼,其在此實例是一個數字之間的一個或多個空格,但它也可以是幾種不同的數字或字符串。 $newstr不需要複製$oldstr中的空格。另外,在上例中,它使用Contains中的三個條件之一。實際數據可能包含無,一個,兩個或全部三個字符串。

你怎麼能做匹配/包含和替換可以有空白的字符串?

+0

好,你就需要正則表達式來做到這一點),但我不能幫你;) – 4c74356b41

回答

2

使用正則表達式與-replace操作者:

PS C:\> '"status":  0' -replace '"status":\s*0','"status": 1' 
"status": 1 
PS C:\> '"status": 0' -replace '"status":\s*0','"status": 1' 
"status": 1 
PS C:\> '"status":0' -replace '"status":\s*0','"status": 1' 
"status": 1 

在圖案I中使用:

  • "status":文字串正好匹配"status":
  • \s*匹配0或多個空格字符
  • 0比賽一個字面0
1

Here is an interessant solution有幾個匹配/替換對與散列表轉換成組合正則表達式。但是我沒有得到一個正則表達式進入散列鍵,所以我在表單和RegEx中都對foreach中的$ _進行了處理。

# Build hashtable of search and replace values. 

$file = ".\testfile.txt" 

$replacements = @{ 
    'something2' = 'somethingelse2' 
    'something3' = 'somethingelse3' 
    'morethings' = 'morethingelses' 
    'blabla' = 'blubbblubb' 
} 
# Join all keys from the hashtable into one regular expression. 
[regex]$r = @($replacements.Keys | foreach { [regex]::Escape($_) }) -join '|' 

[scriptblock]$matchEval = { param([Text.RegularExpressions.Match]$matchInfo) 
    # Return replacement value for each matched value. 
    $matchedValue = $matchInfo.Groups[0].Value 
    $replacements[$matchedValue] 
} 
$fileCont = Get-Content $file 
# Perform replace over every line in the file and append to log. 
$Newfile = $fileCont | ForEach { 
    $r.Replace(($_ -replace '"status":\s*0','"status": 1'), $matchEval) 
} 

$fileCont 
"----" 
$Newfile 

給出了這樣的輸出構成了我TESTFILE.TXT

> .\Replace-Array.ps1 
"Status": 0, something2,morethings 
"Status": 0, something3, blabla 
---- 
"status": 1, somethingelse2,morethingelses 
"status": 1, somethingelse3, blubbblubb