4

I've searched for a fair amount for the answer but all I get is how I do it with multiple Strings. I'm pretty new to PowerShell but want to know how I can manage to do it.

I simply want to remplace the first occurence of "1" with "2" ... I only can close to it but no more. The code I found was:

Get-ChildItem "C:\TEST\1.etxt" | foreach {
$Content = Get-Content $_.fullname
$Content = foreach { $Conten -replace "1","2" }
Set-Content $_.fullname $Content -Force
}

The content of the txt is just random: 1 1 1 3 3 1 3 1 3 ... for keeping it simple.

Could someone please explain how I do it with the first occurence and if it is possible and not to time consuming how I can replace for example the 3rd occurrence?

2 Answers 2

6

Same answer as Martin but a bit more simplified so you might better understand it:

$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'

If you want this in a one-liner:

([Regex]'1').Replace('1 1 1 3 3 1 3 1 3','2',1)

Found this information here.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thanks. That I got without thinking to hard. :)
1

You could use a positive lookahead to find the position of the first 1 and capture everything behind. Then you replace the 1 with 2 and the rest of the string using the capture group $1:

"1 1 1 3 3 1 3 1 3" -replace '(?=1)1(.*)', '2$1'

Output:

2  1 1 3 3 1 3 1 3

To caputre the third occurence, you could do something like this:

"1 1 1 3 3 1 3 1 3" -replace '(.*?1.*?1.*?)1(.*)', '${1}2$2'

Output:

1 1 2 3 3 1 3 1 3

1 Comment

It does work. Now I just have to find out what exactly every stept does, but I think I will figure out that myself with some research. Thanks you for your response. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.