【发布时间】:2017-02-16 15:16:40
【问题描述】:
我在名为“.connectionInfo”的文件中有以下文本:
device name = "WTG001" {
address = "172.28.16.1";
port = 80;
timeout = 3;
rfs = true;
operatingSystem = "vxworks";
}
我有一个文件作为主文件(如上所示),并希望在多个目录中创建多个副本,此 IP 地址加一。在目录“WTG001”中,我将拥有带有“172.28.16.1”的.connectionInfo,在目录“WTG002”中,我将拥有带有“172.28.16.2”的.connectionInfo,等等。
我有以下 Powerscript 文件,并想使用计数器 (IP_Counter) 来增加 IP 地址的最后一位数:
$folder="C:\work\Scripting";
$txtFile="C:\work\Scripting\TurbineConfig.txt";
$pattern="\d+.+";
get-content $txtFile | %
{
$IP_Counter = 1
if($_ -match $pattern)
{
Copy-Item -Path C:\work\Scripting\.connectionInfo -Destination "$folder\$_.vxworks";
(Get-Content C:\work\Scripting\.connectionInfo) |
Foreach-Object {$_ -replace '172.28.16.*','172.28.16.$IP_Counter'} |
Out-File "$folder\.connectionInfo";
$IP_Counter++;
...
}
}
我对“-replace”属性的正确语法有疑问。我只想用值 $IP_Counter 替换 IP 地址的最后 3 位数字。我认为使用 '172.28.16.*' 通配符 finds IP 中的最后一个数字,但我无法弄清楚 replace 字符串。请帮我确定 '172.28.16.$IP_Counter' 应该是什么样子。
我也可以使用相同的知识来替换“WTG001”文本。
【问题讨论】:
-
-replace使用正则表达式,在正则表达式中,点是任何字符。要匹配文字点,您必须使用反斜杠转义。所以Foreach-Object {$_ -replace '172\.28\.16\.\d{1,3}',"172.28.16.$IP_Counter"}也不会扩展单引号中的变量。
标签: shell powershell