【问题标题】:Powershell: find/replace string using wildcard - syntax difficultyPowershell:使用通配符查找/替换字符串 - 语法困难
【发布时间】: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


【解决方案1】:

您可以使用以下-replace 表达式:

Foreach-Object {$_ -replace '172\.28\.16\.\d+',"172.28.16.$IP_Counter"}

\d+ 仅代表数字,因此行尾的分号和引号不会被替换。您还需要在替换字符串周围使用双引号 " 来插入 $IP_Counter

我希望对$IP_Counter 也有一些边界检查 - 在您的示例中,它看起来会永远循环。

【讨论】:

    猜你喜欢
    • 2016-10-08
    • 2023-04-04
    • 2021-12-19
    • 1970-01-01
    • 2021-12-11
    • 2014-12-03
    • 2017-06-15
    • 1970-01-01
    • 2013-02-23
    相关资源
    最近更新 更多