2

I am trying to replace a | character within a text file. But I am not sure how to do it because the batch is not reading the |.

powershell -Command "(gc output.txt) -replace '|', ' ' | Out-File -encoding ASCII output.txt"

Which takes this input: 80853||OHNED|Mira

And outputs: 8 0 8 5 3 | | O H N E D | M i r a

Where I'd like this output 80853 OHNED Mira

Is there anyway within a batch to replace the | character?

Edit - While googling, I found out that the | character is called a vertical bar.

mklement0
  • 382,024
  • 64
  • 607
  • 775
moveit124
  • 61
  • 8
  • 2
    the pipe `|` is special character in regex and `-replace` is a regex compatible operator. preferable, since you want to replace a literal pipe, you should use a replacement method that replaces characters literally: `(gc output.txt -Raw).Replace('|', ' ') ....` – Santiago Squarzon Sep 27 '22 at 01:51

2 Answers2

4

PowerShell's -replace operator is regex-based; since your intent is to replace all | characters verbatim, you must escape | as \|, given that | is a regex metacharacter (a character with special meaning in the context of a regex (regular expression)):

powershell -Command "(gc output.txt) -replace '\|', ' ' | Out-File -encoding ASCII output.txt"

In cases where escaping individual characters isn't an option or would be cumbersome - e.g. if you're given a search string that you want to treat literally, as a whole - use [regex]::Escape():

powershell -Command "(gc output.txt) -replace [regex]::Escape('|'), ' ' | Out-File -encoding ASCII output.txt"

Alternatively, in your simple case you could use the .Replace() string method, which invariably performs verbatim replacements and therefore does not require escaping:

powershell -Command "(gc output.txt).Replace('|', ' ') | Out-File -encoding ASCII output.txt"

Note:

  • Unlike PowerShell's operators, the [string] type's .Replace() method is case-sensitive, invariably so in Windows PowerShell, and by default in PowerShell (Core) 6+.

See also:

  • For general guidance on when to use PowerShell's -replace operator vs. the .NET [string] type's .Replace() method, see the bottom section of this answer.

  • For robustly escaping all metacharacters in a -replace search regex and/or in its replacement operand in order to treat one or both as verbatim strings, see this answer.

mklement0
  • 382,024
  • 64
  • 607
  • 775
2

Edit : This can did the trick to replace the special char :

@echo off
powershell -Command "(gc input.txt -raw) -replace '([\^&<>\|\(\)!])', ' ' | Out-File output.txt"
start "" output.txt
Hackoo
  • 18,337
  • 3
  • 40
  • 70