字符串替换在PowerShell中不起作用

时间:2018-12-23 22:18:47

标签: string powershell replace

我对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"

1 个答案:

答案 0 :(得分:0)

您已经发现了解决以下问题的关键,即意识到您尝试从诸如x之类的行中提取x = 123的缺陷在于它提取了(尾随空格)。

最简单的解决方法是简单地从substring-extraction语句的结果中修剪空格(请注意.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

}