问题
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
- `|
- '|'
- |
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.
回答1:
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.
回答2:
Use the -SimpleMatch
parameter for Select-String
, which turns off regular expression matching.
来源:https://stackoverflow.com/questions/34231674/unable-to-escape-pipe-character-in-powershell