Replace the content of a textfile with a regex in powershell Replace the content of a textfile with a regex in powershell powershell powershell

Replace the content of a textfile with a regex in powershell


Yes, you can do that in one line and don't even need a pipeline, as -replace works on arrays like you would expect it to do (and you can chain the operator):

(Get-Content Input.json) `    -replace '"(\d+),(\d{1,})"', '$1.$2' `    -replace 'second regex', 'second replacement' |  Out-File output.json

(Line breaks added for readability.)

The parentheses around the Get-Content call are necessary to prevent the -replace operator being interpreted as an argument to Get-Content.


Is it possible to write it in one line without the content variable, like this?

Yes: use ForEach-Object (or its alias %) and then $_ to reference the object on the pipeline:

Get-Content -path "Input.json" | % { $_ -Replace '"(\d+),(\d{1,})"', '$1.$2' } |  Out-File "output.json"

Is it possible to do more replacements than one in a pipeline.

Yes.

  1. As above: just adding more Foreach-Object segments.
  2. As -replace returns the result, they can be chained in a single expression:

    ($_ -replace $a,$b) -replace $c,$d

    I suspect the parentheses are not needed, but I think they make it easier to read: clearlymore than a few chained operators (especially if the match/replacements are non-trivial) willnot be clear.