2

I have a file with the same text occurring 5 times in total. I now want to only replace the first 2 occurrences with a powershell command within a batch file.

Hello -- I want to only
Hello -- replace those.
Hello
Hello
Hello

So my file will look like that:

Goodbye
Goodbye
Hello
Hello
Hello

My code looks like that:

powershell -command "$null=new-item -force test.txt -value ((gc -encoding utf8 test.txt) -replace ('^.*$','Goodbye') | out-string)"

I tried using the answer to Replacing only the first occurrence of a word in a string:

powershell -command "$null=new-item -force test.txt -value ((gc -encoding utf8 test.txt) -replace ('^.*$','Goodbye',2) | out-string)"

Which gave me the BadReplaceArgument error.

leiseg
  • 105
  • 6

1 Answers1

2

It seems like you're looking for a direct call to the Regex.Replace API, certainly the -replace operator doesn't have an overload for count.

$re = [regex]::new('^.*', [System.Text.RegularExpressions.RegexOptions]::Multiline)

$re.Replace(@'
Hello
Hello
Hello
Hello
Hello
'@, 'Goodbye', 2)

If doing a CLI call the following might work (note, the use of -Raw on Get-Content is very important here!):

powershell -Command @'
$re = [regex]::new('^.*', [System.Text.RegularExpressions.RegexOptions]::Multiline)
$re.Replace((Get-Content -Encoding utf8 test.txt -Raw), 'Goodbye', 2) |
    Set-Content test.txt
'@
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • I tried using the CLI call but it didn't work. The console closes itself when trying to execute the command. That's the code I am trying to run: ```powershell -Command @' $re = [regex]::new('^SceneCaptureStreamingMultiplier *=.*', [System.Text.RegularExpressions.RegexOptions]::Multiline) $re.Replace((Get-Content -Encoding utf8 test.txt -Raw), 'SceneCaptureStreamingMultiplier=1.000000', 2) | Set-Content test.txt '@``` – leiseg Apr 30 '23 at 08:20
  • 2
    @leiseg, Santiago's syntax only works from _inside_ PowerShell. From `cmd.exe`, use a single-line `"..."` string as the `-Command` argument. – mklement0 May 01 '23 at 20:46
  • 1
    @mklement0 This works! Thank you once again. – leiseg May 02 '23 at 06:59