Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to escape pipe character (|) in powershell

I am trying to find number of pipe(|) characters in each line of a file. I am using following command to do so.

gc .\test.txt | % { ($_ | select-string "|" -all).matches | measure | select count }

Its not counting the pipe symbol.

I also tried

  1. `|
  2. '|'
  3.  |

Can anyone tell me how to escape pipe character in power shell?

If i am using strings or characters other than pipe the command is working properly.

like image 966
Rajeev Avatar asked Oct 22 '25 13:10

Rajeev


1 Answers

A backslash \ is the escape character for a regular expression.

gc .\test.txt | % { ($_ | select-string "\|" -all).matches | measure | select count }

If you're unsure, you can always use [RegEx]::Escape():

$pattern = [RegEx]::Escape("|")
gc .\test.txt | % { ($_ | select-string $pattern -all).matches | measure | select count }

The pipe otherwise does not have to be escaped in PowerShell inside a string.

like image 87
briantist Avatar answered Oct 24 '25 06:10

briantist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!