I have a simple textfile and I need a powershell script to replace some parts of the file content.
My current script is the following:
$content = Get-Content -path "Input.json"
$content -Replace '"(\d+),(\d{1,})"', '$1.$2' | Out-File "output.json"
Is it possible to write it in one line without the content variable, like this?
Get-Content -path "Input.json" | ??? -Replace '"(\d+),(\d{1,})"', '$1.$2' | Out-File "output.json"
I don't know how I can use the output of the first get-content commandlet in the second command without the $content variable? Is there an automatic powershell variable
Is it possible to do more replacements than one in a pipeline.
Get-Content -path "Input.json" | ??? -Replace '"(\d+),(\d{1,})"', '$1.$2' | ??? -Replace 'second regex', 'second replacement' | Out-File "output.json"
Yes: use
ForEach-Object
(or its alias%
) and then$_
to reference the object on the pipeline:Yes.
Foreach-Object
segments.As
-replace
returns the result, they can be chained in a single expression:I suspect the parentheses are not needed, but I think they make it easier to read: clearly more than a few chained operators (especially if the match/replacements are non-trivial) will not be clear.
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):(Line breaks added for readability.)
The parentheses around the
Get-Content
call are necessary to prevent the-replace
operator being interpreted as an argument toGet-Content
.