user7656612
user7656612

Reputation:

Powershell - Match and replace

Trying to match and replace, while keeping order of content in file.

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

The output is:

<source src="video_1.mp4">
<source src="video_2.mp4">

But I'm trying to have it:

<img src="img_a.PNG">
<source src="video_1.mp4">
<img src="img_b.PNG">
<source src="video_2.mp4">

Seems to be overwriting it?

Upvotes: 1

Views: 399

Answers (1)

mklement0
mklement0

Reputation: 437218

Try the following:

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

This could be made more robust, but works with the sample input.

The above relies on:

  • a (positive) lookahead assertion ((?=...)) that matches part of the input without considering it part of the overall match and therefore not replacing it.

  • -replace passing any non-matching inputs through as-is.


As for what you tried:

By only producing output if condition if ($_ -match ".mp4") is true, you're effectively omitting the input lines that do not match .mp4.

Upvotes: 1

Related Questions