string - Windows gc 替换显示\n 而不是新行

标签 string powershell

这是我在 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

这是test.txt:

ok
ok
ok

这是当前的test2.txt:

this is a repl ok\ntest tex ok test

虽然应该是:

first ok
second ok third

我也尝试过,但出现以下错误:

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

错误:

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

我也尝试过这个(这在 Linux 中有效,但在 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'

如何查找和替换正则表达式?

我搜索了 google 和 stackoverflow 并尝试了一些命令,但它们在我的问题中显示了 \n ,如上面所示。

最佳答案

PowerShell 中的单引号内不支持字符串转义序列。 '\n 是文字 \ 后跟文字 n 字符的序列。

您需要使用双引号,然后使用反引号 + n 插入换行符,即 "`n"。所以,使用

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

关于string - Windows gc 替换显示\n 而不是新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72498871/

相关文章:

带有多个字符定界符的 Java String.split

c++ - 在 C++ 中将 Double 转换为 String 的问题

Java 子串迭代问题

PowerShell管道

javascript - 一个字符串多个变量用indexOf检查

c++在序列之前删除字符串中的所有内容,包括序列

powershell - 在 Sitecore powershell 中,您能否将项目设为不可发布

powershell - 删除未锁定(正在使用)的文件

powershell - 按文件名重命名报告

events - PowerShell:如何在远程服务器上运行脚本?