Home > Enterprise >  Replace Vertical bar within a text file
Replace Vertical bar within a text file

Time:09-27

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.

CodePudding user response:

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"

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"

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.

CodePudding user response:

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
  • Related