0

I have a text file called "delete.txt". The content is

My name is "David", "David" 

I want to replace the second "David" with "Hello". I can only replace both of them with this:

$David = Get-Content -path C:\Users\David\Documents\delete.txt 
$David -replace "David", "Hello" | Out-File C:\Users\David\Documents\delete.txt  

There could be more "David"'s in the file but I just want to replace the second one.

3
  • 1
    So you might look for the comma in front of the "David" as well. Or you search for "David" followed by the end of the line. It depends how your input file looks. Commented Sep 19, 2020 at 14:50
  • @Olaf. Thansk this way of thinking actually solves my problem :-) But just out of curiosity is there a way to find the position of the start of the two "David"s Commented Sep 19, 2020 at 14:56
  • 1
    Of course ... take a look at the cmdlet Select-String Commented Sep 19, 2020 at 14:59

1 Answer 1

1

You can simply do:

$David -replace '"David", "David"','"David", "Hello"' | Out-File C:\Users\David\Documents\delete.txt
Sign up to request clarification or add additional context in comments.

1 Comment

This works too, thanks. The comment from from Olaf works too... Also your answer from yesterday has helped me a lot, especially the trick with parentheses

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.