string - 字符串替换在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"
。
解决方案
您已经找到了解决您自己问题的关键,因为您意识到您尝试x
从一行中提取x = 123
是有缺陷的,因为它提取的是x
(带有尾随空格)。
最简单的解决方法是从子字符串提取语句的结果中简单地修剪空格(注意.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
}
推荐阅读
- azure - 登录页面上未显示 Azure Active Directory 公司品牌
- build - CMake:c 编译器无法编译简单的测试程序。它失败并显示以下输出
- python-3.x - 3个数据集的python条形图
- python - 如何使用 ctypes 接收 wchar_t * 字符串
- python - Python FitBit 库。“授权错误:授权令牌类型无效”
- python - 如何按多列的时间戳对数据帧进行排序
- python - 将图像缩放到给定特定范围的通用方法
- jquery - 在 WooCommerce 中隐藏特定计费状态的一些结帐字段类型
- java - Spring 在服务器上运行良好,但在主应用程序上运行良好
- macos - 在 Mac OS 上编译时使用 Clang 时出错