替换第一个副本没有正则表达式和增量

时间:2017-09-26 13:57:10

标签: powershell duplicates

我有一个文本文件,我在文件中的某处有3个相同的数字。我需要使用PowerShell逐步添加每个。

以下是我目前的代码。

$duped = Get-Content $file | sort | Get-Unique
while ($duped -ne $null) {
    $duped = Get-Content $file | sort | Get-Unique | Select -Index $dupecount
    $dupefix = $duped + $dupecount
    echo $duped
    echo $dupefix
    (Get-Content $file) | ForEach-Object {
        $_ -replace "$duped", "$dupefix"
    } | Set-Content $file
    echo $dupecount
    $dupecount = [int]$dupecount + [int]"1"
}

原始

12345678
12345678
12345678

预期结果:

123456781
123456782
123456783

2 个答案:

答案 0 :(得分:0)

让我们看看我是否正确理解了这个问题:

你有一个X行数的文件:

  1. 一句话
  2. 12345678
  3. 第二个字
  4. 12345678
  5. 第三个字
  6. 您希望捕获12345678的每个实例并为其添加1个增量,以便它变为:

    1. 一句话
    2. 12345679
    3. 第二个字
    4. 12345679
    5. 第三个字
    6. 这是你想要做的吗?

答案 1 :(得分:0)

$filecontent = (get-content C:\temp\pos\bart.txt )
$output = $null
[int]$increment = 1
foreach($line in $filecontent){  

    if($line -match '12345679'){            
            $line = [int]$line + $increment
            $line 
            $output +=  "$line`n"
            $increment++
    }else{       
        $output += "$line`n"
    }
}
$output | Set-Content -Path C:\temp\pos\bart.txt -Force 

这适用于我对5行的测试

  1. 一句话
  2. 12345679
  3. 第二个字
  4. 12345679
  5. 第三个字
  6. 输出将是:

    1. 一句话
    2. 12345680
    3. 第二个字
    4. 12345681
    5. 第三个字