Home > Net >  Powershell Get-Content -> Parameter "-replace"
Powershell Get-Content -> Parameter "-replace"

Time:04-27

Hi!

  • Is the "-replace" Parameter bounded to the cmdlet "Get-Content"? through googling i found it in many different contexts
  • Why is the -replace Parameter not shown in the official Documentation? Get-Content Microsoft

Issue:

The text apporaches like this:

olor sit amet, consetetur sadipscing elitr, sed diam nonumy LoremIpsum-648648sdfsd

I want to replace the substring via Regex from "LoremIpsum-xxx" to "Loremipsum"

This is my first Try:

(Get-Content "C:\File.cmd") -replace "[regex]::matches("LoremIpsum-(.*?)")" | Out-File -encoding ASCII C:\File.cmd

CodePudding user response:

-replace is not a Get-Content parameter, it is an operator that allows to use a regular expression to find a specified pattern and then either remove or replace the matched text with another.

In your case, you can use

(Get-Content "C:\File.cmd") -replace '(?<=\bLoremIpsum)-\w ' | Out-File -encoding ASCII C:\File.cmd

The (?<=\bLoremIpsum)-\w regex matches a hyphen (-) and one or more word chars (\w ) that are immediately preceded with a LoremIpsum as a whole word (\b is a word boundary).

Note you may replace \w with \S if you want to remove any one or more non-whitespace chars after LoremIpsum.

Alternatively, you can use

(Get-Content "C:\File.cmd") -replace '\b(LoremIpsum)-\w ', '$1' | Out-File -encoding ASCII C:\File.cmd

Here, LoremIpsum is captured into a capturing group (with ID 1 since it is the first capturing group in the regex), and the replacement is now $1, the replacement backreference referring to Group 1 value.

See the regex demo #1 and this regex demo.

  • Related