[英]powershell -replace regex
I have the following script which I try to run on various html files 我有以下脚本,我尝试在各种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
}
}
in an attempt to edit this line found in all the files. 试图编辑在所有文件中找到的这一行。
<tr><td><a href="sampleTest.html">TestCase</a></td></tr>
I call the script from powershell like this (it's called replace.ps1) 我像这样从powershell调用脚本(称为replace.ps1)
./replace *.html sampleTest myNewTest
but instead of changing sampleTest.html to myNewTest.html it deletes everything in the doc except for the last line, leaving all of the files like so: 但是它没有删除sampleTest.html到myNewTest.html,而是删除了文档中除最后一行以外的所有内容,保留了所有文件,如下所示:
/html
in fact, no matter what arguments I pass in this seems to happen. 实际上,无论我通过什么论点,这似乎都在发生。 Can anyone explain this/help me understand why it's happening? 谁能解释这个/帮助我理解为什么会这样?
Your loop structure is to blame here. 您的循环结构应归咎于此。 You need to have the Set-Content
located outside the loop. 您需要将Set-Content
位于循环外部。 Your code is overwriting the file at every pass. 您的代码会在每次通过时覆盖文件。
....
foreach-object { $a = $_.fullname; ( get-content $a ) |
foreach-object {
$_ -replace "$string1" , "$string2" |
} | set-content $a
}
It also might have been a typo but you had "%string1"
before which, while syntactically correct, what not what you intended. 它也可能是拼写错误,但是在语法上正确的情况下,您之前有"%string1"
,但并不是您想要的。
Could also have used Add-Content
but that would mean you have to erase the file first. 也可以使用Add-Content
但这意味着您必须先删除文件。 set-content $a
used at the end of the pipe is more intuitive. 管道末端使用的set-content $a
更直观。
Your example is not one that uses regex. 您的示例不是使用正则表达式的示例。 You could have used $_.replace($string1,$string2)
with the same results. 您本可以使用$_.replace($string1,$string2)
获得相同的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.