Unable to escape pipe character (|) in powershell

对着背影说爱祢 提交于 2019-12-23 17:33:33

问题


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.


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!