1

I need to edit txt file using PowerShell. The problem is that I need to apply changes for the string only if the remaining part of the string matches some pattern. For example, I need to change 'specific_text' to 'other_text' only if the line ends with 'pattern':

'specific_text and pattern' -> changes to 'other_text and pattern'

But if the line doesn't end with pattern, I don't need to change it:

'specific_text and something else' -> no changes

I know about Replace function in PowerShell, but as far as I know it makes simple change for all matches of the regex. There is also Select-String function, but I couldn't combine them properly. My idea was to make it this way:

((get-content myfile.txt | select-string -pattern "pattern") -Replace "specific_text", "other_text") | Out-File myfile.txt

But this call rewrites the whole file and leaves only changed lines.

2
  • 1
    -Replace "specific_text(?=.*pattern$)", "other_text" Commented Jul 27, 2020 at 8:40
  • Thank you, @WiktorStribiżew! If you want, you can write it as an answer and I'll accept it Commented Jul 27, 2020 at 9:14

1 Answer 1

1

You may use

(get-content myfile.txt) -replace 'specific_text(?=.*pattern$)', "other_text" | Out-File myfile.txt

The specific_text(?=.*pattern$) pattern matches

  • specific_text - some specific_text...
  • (?=.*pattern$) - not immediately followed with any 0 or more chars other than a newline as many as possible and then pattern at the end of the string ($).
Sign up to request clarification or add additional context in comments.

Comments

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.