Powershell-替换字符串的第一次出现

Ill*_*var 2 string powershell replace

我已经搜索了相当多的答案,但我得到的只是如何使用多个字符串来做到这一点。我对 PowerShell 还很陌生,但想知道如何做到这一点。

我只是想用“2”替换第一次出现的“1”......我只能接近它,但不能再接近它了。我找到的代码是:

Get-ChildItem "C:\TEST\1.etxt" | foreach {
$Content = Get-Content $_.fullname
$Content = foreach { $Conten -replace "1","2" }
Set-Content $_.fullname $Content -Force
}
Run Code Online (Sandbox Code Playgroud)

txt 的内容只是随机的:1 1 1 3 3 1 3 1 3...为了保持简单。

有人可以解释我如何在第一次出现时做到这一点吗?如果可能并且不耗时,我如何替换例如第三次出现?

Dar*_*te1 5

与 Martin 的答案相同,但更简单一些,这样您可能会更好地理解它:

$R=[Regex]'1'
#R=[Regex]'What to replace'

$R.Replace('1 1 1 3 3 1 3 1 3','2',1)
#R.Replace('Oringinal string', 'Char you replace it with', 'How many')

#Result = '2 1 1 3 3 1 3 1 3'
Run Code Online (Sandbox Code Playgroud)

如果你想在一行中做到这一点:

([Regex]'1').Replace('1 1 1 3 3 1 3 1 3','2',1)
Run Code Online (Sandbox Code Playgroud)

在这里找到了这个信息。