Home > Mobile >  Windows gc replace shows \n instead of new line
Windows gc replace shows \n instead of new line

Time:06-04

This is what I use in PowerShell 5.1:

(gc test.txt) | ForEach-Object {$_ -replace '^(.*)(\r?\n|$)', '^(.*)(\r?\n|$)', 'this is a repl $1\ntest tex $1 test$2'} | Set-Content test2.txt

This is test.txt:

ok
ok
ok

This is the current test2.txt:

this is a repl ok\ntest tex ok test

While it should be:

first ok
second ok third

I also tried this but got the following error:

sed -re "s|^(.*)(\r?\n|$)|this is a repl $1\ntest tex $1 test$2" test.txt > test2.txt

Error:

/usr/bin/sed: -e expression #1, char 19: unknown option to `s'

I also tried this (this works in Linux but not in Windows):

sed -e "s|^(.*)(\r?\n|$)|this is a repl $1\ntest tex $1 test$2" -i test.txt
/usr/bin/sed: -e expression #1, char 19: unknown option to `s'

How to find and replace regex?

I searched google and stackoverflow and tried some commands but they showed \n like above in my question.

CodePudding user response:

Inside single quotes in PowerShell, no string escape sequences are supported. '\n is a sequence of a literal \ followed with a literal n char.

You need to use double quotes and then use backtick n to insert a newline, i.e. "`n". So, use

"this is a repl `$1`ntest tex `$1 test`$2"
  • Related