2015-11-11 60 views
2

我有以下脚本,我尝试在试图改变这一行中的所有文件中找到各种HTML文件PowerShell的-replace正则表达式

$files = $args[0]; 
$string1 = $args[1]; 
$string2 = $args[2]; 
Write-Host "Replace $string1 with $string2 in $files"; 
gci -r -include "$files" | 
foreach-object { $a = $_.fullname; (get-content $a) | 
    foreach-object { 
      $_ -replace "%string1" , "$string2" | 
      set-content $a 
    } 
} 

运行。

<tr><td><a href="sampleTest.html">TestCase</a></td></tr> 

我调用脚本从这样的PowerShell(这就是所谓的replace.ps1)

./replace *.html sampleTest myNewTest 

,而不是改变sampleTest.html到myNewTest.html 它删除一切都在文档除外,但最后一行, 使所有像这样的文件:

/html 

其实,不管我通过在这个什么样的参数似乎发生。 任何人都可以解释这个/帮助我理解为什么会发生?

回答

3

你的循环结构是在这里责怪。您需要将Set-Content定位在循环外部。您的代码每次都会覆盖文件。

.... 
foreach-object { $a = $_.fullname; (get-content $a) | 
    foreach-object { 
      $_ -replace "$string1" , "$string2" |   
    } | set-content $a 
} 

它也可能是一个错字,但你收到这"%string1",而语法正确,你打算什么不是。

也可以使用Add-Content但这意味着您必须先擦除文件。 set-content $a用于管道末端更直观。


你的例子不是使用正则表达式的例子。您可以使用$_.replace($string1,$string2)获得相同的结果。