替换文本文件中的竖线

问题描述 投票:0回答:2

我正在尝试更换 |文本文件中的字符。但我不确定该怎么做,因为批处理没有读取 |。

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
2个回答
4
投票

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"

注:

  • 与 PowerShell 的运算符不同,
    [string]
    类型的
    .Replace()
    方法区分大小写总是 在 Windows PowerShell 中如此,默认情况下 在 PowerShell (Core) 6+ 中。

另见:

  • 有关何时使用 PowerShell 的

    -replace 运算符与 .NET

    [string]
    类型的
    .Replace()
    方法的
    一般指南
    ,请参阅
    this answer 的底部部分。

  • 对于

    robustly escape all metacharacters in a -replace

     search regex and/or in its replacement operand
    order to treat one or both as verbatim strings, see this answer.


2
投票
编辑:这可以用来替换特殊字符:

@echo off powershell -Command "(gc input.txt -raw) -replace '([\^&<>\|\(\)!])', ' ' | Out-File output.txt" start "" output.txt
    
© www.soinside.com 2019 - 2024. All rights reserved.