morez890
morez890

Reputation: 57

Find replace regex string using powershell (in cmd)

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.

Upvotes: 1

Views: 228

Answers (1)

lit
lit

Reputation: 16236

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

Upvotes: 1

Related Questions