我有以下脚本,我尝试在各种html文件上运行
$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
实际上,无论我通过什么论点,这似乎都在发生。
谁能解释这个/帮助我理解为什么会这样?
最佳答案
您的循环结构应归咎于此。您需要将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)
获得相同的结果。
关于regex - powershell-替换正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33660216/