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