PowerShell Get-Content并替换特定行中的对象

时间:2013-07-24 10:23:35

标签: regex powershell

我有一个包含以下内容的文本文件:

Static Text MachineA MachineB MachineC
Just Another Line

第一行有两个静态词(静态文本),其间有空格。在这两个单词之后有0个或更多计算机名称,也用空格分隔。

如果有0台计算机,但是如果有1台或更多台计算机,我需要找到一种方法将文本添加到第一行(第二行不会更改)。我需要用新的计算机名替换所有计算机名。所以脚本应该编辑文件来得到这样的东西:

Static Text MachineX MachineY
Just Another Line

我用Regex查看了-replace函数,但无法弄清楚它为什么不起作用。这是我的脚本:

$OptionsFile = "C:\scripts\OptionsFile.txt"
$NewComputers = "MachineX MachineY"

$content = Get-Content $OptionsFile
$content |
  ForEach-Object {  
    if ($_.ReadCount -eq 1) { 
      $_ -replace '\w+', $NewComputers
    } else { 
      $_ 
    }
  } | 
  Set-Content $OptionsFile

我希望有人可以帮我解决这个问题。

2 个答案:

答案 0 :(得分:3)

如果Static Text没有出现在文件的其他位置,您只需执行此操作:

$OptionsFile = "C:\scripts\OptionsFile.txt"
$NewComputers = "MachineX MachineY"

(Get-Content $OptionsFile) -replace '^(Static Text) .*', "`$1 $NewComputers" |
    Set-Content $OptionsFile

如果Static Text可以出现在其他位置,并且您只想替换第一行,则可以执行以下操作:

$OptionsFile = "C:\scripts\OptionsFile.txt"
$NewComputers = "MachineX MachineY"

(Get-Content $OptionsFile) | % {
  if ($_.ReadCount -eq 1) {
    "Static Text $NewComputers"
  } else {
    $_
  }
} | Set-Content $OptionsFile

如果您只知道Static Text由第一行中的两个单词组成,但不知道它们究竟属于哪个单词,那么这样的话应该有效:

$OptionsFile = "C:\scripts\OptionsFile.txt"
$NewComputers = "MachineX MachineY"

(Get-Content $OptionsFile) | % {
  if ($_.ReadCount -eq 1) {
    $_ -replace '^(\w+ \w+) .*', "`$1 $NewComputers"
  } else {
    $_
  }
} | Set-Content $OptionsFile

答案 1 :(得分:1)

检查行是否以“静态文本”开头,后跟一系列单词字符,如果匹配则返回字符串:

Get-Content $OptionsFile | foreach {    
  if($_ -match '^Static Text\s+(\w+\s)+')
  {
      'Static Text MachineX MachineY'
  }
  else
  {
      $_
  }
}