Powershell - 匹配和替换

时间:2018-06-02 00:37:01

标签: powershell

尝试匹配和替换,同时保持文件内容的顺序。

(Get-Content output.txt) |
    ForEach-Object { if ($_ -match ".mp4") {$_ -replace "img", "source"} } | Set-content output.txt

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">

似乎要覆盖它?

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

(Get-Content output.txt) -replace '<img (?=.+\.mp4)', '<source ' |
  Set-Content output.txt

这可以更加健壮,但可以使用示例输入。

以上依赖于:

  • 一个(正面的)先行断言((?=...)),它匹配部分输入而不将其视为整体匹配的一部分,因此不会替换它。

  • -replace通过原样传递任何不匹配的输入。

至于您尝试的内容

仅在条件if ($_ -match ".mp4")为真时生成输出,您实际上省略.mp4不匹配的输入行。