替换没有正则表达式的第一个重复项并递增 [英] Replace first duplicate without regex and increment
本文介绍了替换没有正则表达式的第一个重复项并递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文本文件,并且文件中某处有3个相同的数字.我需要使用PowerShell逐个添加.
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.
下面是我当前的代码.
$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
推荐答案
$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行时有效
- 一个字
- 12345679
- 第二个字
- 12345679
- 第三个字
输出为:
- 一个字
- 12345680
- 第二个字
- 12345681
- 第三个字
这篇关于替换没有正则表达式的第一个重复项并递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文