1

I want to find regex string in a txt file, replace it with other regex string and output it to new txt file. I wanna use powershell commands in cmd (batch file).

Now I do this, it works, but can't add new line:

set Test1=.\Test1.txt
powershell -command "& {Get-ChildItem .\LogFULL.txt | Get-Content | Foreach-Object {$_ -replace '\[\+\]PS PLUS:', 'PS PLUS: ' -replace '\[\+\] Country', 'Region' -replace '================TRANSACTIONS================','----- Games -----' -replace '================TRANSACTIONS END============','-----\r\nPlay Time\: 20 Minutes--------------------'}} | Set-Content  -encoding Default .\Test1.txt"

I tried different ways like `r`n or adding and removing -raw, -r, foreach and etc but can't handle it.

4
  • 1
    Try with backslash-escaped double quotes: \"-----`r`nPlay Time: 20 Minutes--------------------\" Commented Nov 18, 2020 at 15:03
  • @Theo not solved. Commented Nov 18, 2020 at 17:32
  • Why not solved? This is exactly what solved it in the answer.. Commented Nov 18, 2020 at 21:26
  • @Theo I tried but doesn't work, maybe because it was inline? Or I had other mistake? Commented Nov 18, 2020 at 21:38

1 Answer 1

1

The escaped characters must be in a string using QUOTATION MARK characters. Also, no invocation operator (&) is needed.

powershell -NoLogo -NoProfile -Command ^
    "Get-ChildItem .\Test1.txt |" ^
    "Get-Content |" ^
    "Foreach-Object { $_ -replace 'is', \"was`r`nwas\" } |" ^
    "Set-Content -encoding Default .\Test2.txt"

The results are:

PS C:\src\t> Get-Content -Path .\Test1.txt
now is the time
PS C:\src\t> Get-Content -Path .\Test2.txt
now was
was the time
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.