尝试匹配和替换,同时保持文件中内容的顺序。
(Get-Content output.txt) | ForEach-Object { if ($_ -match ".mp4") {$_ -replace "img", "source"} } | Set-content output.txt
输出:
<img src="img_a.PNG"> <img src="video_1.mp4"> <img src="img_b.PNG"> <img src="video_2.mp4">
产出如下:
<source src="video_1.mp4"> <source src="video_2.mp4">
但我想要的是:
<img src="img_a.PNG"> <source src="video_1.mp4"> <img src="img_b.PNG"> <source src="video_2.mp4">
似乎是在覆盖它?
发布于 2018-06-07 09:09:52
尝试以下几点:
(Get-Content output.txt) -replace '<img (?=.+\.mp4)', '<source ' |
Set-Content output.txt
这可以使其更健壮,但可以与示例输入一起工作。
以上所依据的是:
(?=...)
)与部分输入匹配,而不考虑它在整体匹配中的一部分。-replace
传递任何不匹配的输入通过原样。至于你试过的:
只在条件下产生输出if ($_ -match ".mp4")
是真的,你实际上省略不匹配的输入行。.mp4
。
https://stackoverflow.com/questions/-100004780
复制相似问题