我正在尝试更换 |文本文件中的字符。但我不确定该怎么做,因为批处理没有读取 |。
powershell -Command "(gc output.txt) -replace '|', ' ' | Out-File -encoding ASCII output.txt"
接受这个输入:
80853||OHNED|Mira
和输出:
8 0 8 5 3 | | O H N E D | M i r a
我想要这个输出的地方
80853 OHNED Mira
无论如何在一个批次中是否有替换 |性格?
编辑 - 在谷歌搜索时,我发现 |字符称为竖线。
PowerShell 的
-replace
运算符基于 regex;由于您的意图是替换所有|
字符verbatim,因此您必须将escape|
作为\|
,因为|
是正则表达式metacharacter(在上下文中具有特殊含义的字符正则表达式(正则表达式)的:
powershell -Command "(gc output.txt) -replace '\|', ' ' | Out-File -encoding ASCII output.txt"
在转义单个字符不是一个选项或者会很麻烦的情况下 - 例如如果你 given 一个你想按字面意义对待的搜索字符串,作为一个整体 - 使用
[regex]::Escape()
:
powershell -Command "(gc output.txt) -replace [regex]::Escape('|'), ' ' | Out-File -encoding ASCII output.txt"
或者,在您的简单情况下,您可以使用
.Replace()
字符串method,它总是执行verbatim替换因此not需要转义:
powershell -Command "(gc output.txt).Replace('|', ' ') | Out-File -encoding ASCII output.txt"
注:
[string]
类型的 .Replace()
方法区分大小写,总是 在 Windows PowerShell 中如此,默认情况下 在 PowerShell (Core) 6+ 中。
@echo off
powershell -Command "(gc input.txt -raw) -replace '([\^&<>\|\(\)!])', ' ' | Out-File output.txt"
start "" output.txt