无法在 powershell 中转义管道字符 (|)

Unable to escape pipe character (|) in powershell

我正在尝试查找文件每一行中管道 (|) 字符的数量。我正在使用以下命令来执行此操作。

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

管道符号不算在内

我也试过了

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

谁能告诉我如何转义管道字符 power shell?

如果我使用的是管道以外的字符串或字符,则该命令运行正常。

反斜杠 \ 是正则表达式的转义字符。

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

如果您不确定,可以随时使用 [RegEx]::Escape():

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

否则管道不必在字符串内的 PowerShell 中转义。

Select-String 使用 -SimpleMatch 参数,这将关闭正则表达式匹配。