Replace the content of a textfile with a regex in powershell

后端 未结 2 1314
半阙折子戏
半阙折子戏 2021-02-03 17:29

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


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-02-03 18:08

    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: clearly more than a few chained operators (especially if the match/replacements are non-trivial) will not be clear.

提交回复
热议问题