首页 > 解决方案 > 字符串替换在powershell中不起作用

问题描述

我的PowerShell有问题。这是我的代码:

$content = [IO.File]::ReadAllText(".\file.js")
$vars = @()

ForEach ($line in $($content -split "`r`n")) {
    if ($line -Match "=") {
        $vars += $line.substring(0,$line.IndexOf("="))
    }
    ForEach ($e in $vars) {
        $line = $line.Replace($e, "$" + $e)
    }
    Write-Host($line)
}

而 file.js 是:

x = 123
(x)

此代码的输出是 $x = 123 和 (x)。(x) 应该是 ($x)。线路$line = $line.Replace($e, "$" + $e) 不工作。

编辑: 好的。问题是 $e 等于"x ",而不是"x"

标签: stringpowershellreplace

解决方案


您已经找到了解决您自己问题的关键,因为您意识到您尝试x从一行中提取x = 123是有缺陷的,因为它提取的是(带有尾随空格)。

最简单的解决方法是从子字符串提取语句的结果中简单地修剪空格(注意.Trim()调用):

# Extract everything before "=", then trim whitespace.
$vars += $line.substring(0,$line.IndexOf("=")).Trim()

但是,请考虑按如下方式简化您的代码:

$varsRegex = $sep = ''

# Use Get-Content to read the file as an *array of lines*.
Get-Content .\file.js | ForEach-Object {

  # See if the line contains a variable assignment.
  # Construct the regex so that the variable name is captured via 
  # a capture group, (\w+), excluding the surrounding whitespace (\s).
  if ($_ -match '^\s*(\w+)\s*=') {
    # Extract the variable name from the automatic $Matches variable.
    # [1] represents the 1st (and here only) capture group.
    $varName = $Matches[1]
    # Build a list of variable names as a regex with alternation (|) and
    # enclose each name in \b...\b to minimize false positives while replacing.
    $varsRegex += $sep + '\b' + $varName + '\b'
    $sep = '|'
  }

  # Replace the variable names with themselves prefixed with '$'
  # Note how '$' must be escaped as '$$', because it has special meaning in 
  # the replacement operand; for instance, '$&' refers to what the regex
  # matched in the input string (in this case: a variable name).
  $line = $_ -replace $varsRegex, '$$$&'

  # Output the modified line.
  # Note: Use Write-Host only for printing directly to the screen.
  $line

}

推荐阅读