问题
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
- a word
- 12345679
- a second word
- 12345679
- a third word
the output would be :
- a word
- 12345680
- a second word
- 12345681
- a third word
回答2:
Let's see if i understand the question correctly:
You have a file with X-amount of lines:
- a word
- 12345678
- a second word
- 12345678
- a third word
You want to catch each instance of 12345678 and add 1 increment to it so that it would become:
- a word
- 12345679
- a second word
- 12345679
- a third word
Is that what you are trying to do?
来源:https://stackoverflow.com/questions/46428476/replace-first-duplicate-without-regex-and-increment