59

我有一个简单的文本文件,我需要一个 powershell 脚本来替换文件内容的某些部分。

我当前的脚本如下:

$content = Get-Content -path "Input.json"

$content -Replace '"(\d+),(\d{1,})"', '$1.$2' |  Out-File "output.json"

是否可以像这样在没有内容变量的情况下将其写在一行中?

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

我不知道如何在没有 $content 变量的情况下在第二个命令中使用第一个 get-content 命令行开关的输出?是否有自动 powershell 变量

是否可以在管道中进行比替换更多的替换。

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

2 回答 2

86

是的,您可以在一行中做到这一点,甚至不需要管道,-replace就像您期望的那样在数组上工作(并且您可以链接运算符):

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

(为了便于阅读,添加了换行符。)

调用周围的括号Get-Content是必要的,以防止-replace运算符被解释为Get-Content.

于 2013-04-27T10:14:14.287 回答
13

是否可以像这样在没有内容变量的情况下将其写在一行中?

是:使用ForEach-Object(或其别名%)然后$_引用管道上的对象:

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

是否可以在管道中进行比替换更多的替换。

是的。

  1. 如上:只是添加更多的Foreach-Object段。
  2. 作为-replace返回结果,它们可以链接在一个表达式中:

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

    我怀疑括号是不需要的,但我认为它们更容易阅读:显然不止一些链式运算符(特别是如果匹配/替换不重要)将不清楚。

于 2013-04-27T10:11:33.303 回答