I'm trying to find and replace some text at the end of line with Powershell. (ascii, txt, windows) I need to do this with a given script, which is already used for string replace:

$inputText = [system.IO.File]::ReadAllText("Text.txt") $regex = '\\DE$|\DE_02' $regex > test.txt $th = [system.IO.File]::ReadAllText("test.txt") foreach($expression in $th) { if ($expression -eq 'EOF') { break } $parts = $expression.Split("|") if ($parts.Count -eq 2) { $inputText = $InputText -creplace $parts echo $inputText | out-file "Text_neu.txt" -enc ascii } } 

The cmdlet works fine so far, but cannot match the end of line ($) -.- I also tried `r`n instead of $ but didn't work...

When I try like this:

$inputText = [system.IO.File]::ReadAllText("Text.txt") $inputText.Replace("\DE\`r\`n","\DE_02\`r\`n") | Out-File Text_neu.txt 

it's al replaced correctly.

How can I change the existing script so that it will work also?

1 Answer

I am not sure if I understand your script correctly, but I think your problem is, you are replacing on the whole text and not on single rows.

So $ is not the end of a row (\r\n) it will per default match on the end of the string!

You can modify this behaviour by using the inline modifier (?m). This will change the behaviour of $ to match the end of the row.

Try

$regex = '(?m)\\DE$|\DE_02' 

as you regular expression.

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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