2016-12-01 87 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