模式替换重复项到文件PowerShell

时间:2017-09-26 17:30:06

标签: regex powershell duplicates

我对同一段代码有一个不同的主题,但问题略有不同(最初的问题是here)。然而,这个困扰了我好几个小时。似乎如果有重复,我不能做替换像

(Get-Content –path $origin) | ForEach-Object {
    $_ -replace "$value", "$newvalue"
} | Set-Content $origin

我的问题是,无论我尝试什么方法,似乎几乎不可能保持初始源文档的完整性,并在更改它们时替换重复值。

我已经能够通过数字循环,但是可用的信息量很少,只能以动态方式修改重复值。我只想浏览每个副本并为其分配不同的数字,而不会弄乱周围的文档。

$duped = Get-Content $file | sort | Get-Unique
if ($duped -ne $null) {
    $filecontent = (Get-Content $file)
    $output = $null
    [int]$increment = 1
    foreach ($line in $filecontent) {
        if ($line -match $duped) {
            $dupefix = $line + $increment
            echo $dupefix
            [regex]$pattern = "$duped"
            $pattern.Replace([string]::Join("", (Get-Content $file )), "$dupefix", $dupecount) |
                Set-Content $origin
            [int]$increment++
            [int]$dupecount++
        }
    }
    $output | Set-Content -Path $file -Force 
    $output | Out-File -Append -Filepath $database -Encoding Ascii
    $duped | Out-File -Append -Filepath $database -Encoding Ascii
}

1 个答案:

答案 0 :(得分:0)

所以,基本上它是选择每个匹配并将修改应用于匹配我正在搜索的字符串的所有内容,而不是单独检查每个副本并修改它。我能够通过使用来弄明白。

(Get-Content $origin) | ForEach-Object { $_ -replace "$duped", ("$duped" + [INT]$dupecount++) } | Set-Content $origin