Replace first duplicate without regex and increment

一曲冷凌霜 提交于 2019-12-24 05:46:56

问题


I have a text file and I have 3 of the same numbers somewhere in the file. I need to add incrementally to each using PowerShell.

Below is my current code.

$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"
}

Original:

12345678
12345678
12345678

Intended Result:

123456781
123456782
123456783

回答1:


$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 

This works in my test of 5 lines being

  1. a word
  2. 12345679
  3. a second word
  4. 12345679
  5. a third word

the output would be :

  1. a word
  2. 12345680
  3. a second word
  4. 12345681
  5. a third word



回答2:


Let's see if i understand the question correctly:

You have a file with X-amount of lines:

  1. a word
  2. 12345678
  3. a second word
  4. 12345678
  5. a third word

You want to catch each instance of 12345678 and add 1 increment to it so that it would become:

  1. a word
  2. 12345679
  3. a second word
  4. 12345679
  5. a third word

Is that what you are trying to do?



来源:https://stackoverflow.com/questions/46428476/replace-first-duplicate-without-regex-and-increment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!