我嘗試創建一個多行 Input 來練習Select-String,期望只輸出一個匹配的行,就像我通常會在echo -e ... | grep組合中看到它一樣。但是下面的命令仍然給了我兩行。似乎換行符只在最終輸出上被解釋并且Select-String仍然得到一行輸入
Write-Output "Hi`nthere" | Select-String -Pattern "i"
#
# Hi
# there
#
#
雖然我希望它回傳
Hi
我使用了這個版本的 PowerShell:
Get-Host | Select-Object Version
# 5.1.19041.906
與bash我相比,我會執行以下操作來測驗 bash 中多行輸入的命令。我通常生成多行,echo -e然后grep處理各行。
echo -e "Hi\nthere" | grep "i"
# Hi
我希望有人能解釋一下我在 PowerShell 中遺漏了什么?這個問題對我來說似乎是一個基本的誤解,我也不知道谷歌是為了什么。
編輯
[編輯 1]:以回車結束的行也有問題
Write-Output "Hi`r`nthere" | Select-String -Pattern "i"
我看到用逗號分隔可以作為有效的多行輸入。所以也許問題是如何從換行符轉換為實際的輸入行分隔。
Write-Output "Hi","there" | Select-String -Pattern "i"
# Hi
[編輯 2]:從編輯 1 開始,我找到了這個 stackoverflow-answer,對我來說它現在可以使用
Write-Output "Hi`nthere".Split([Environment]::NewLine) | Select-String -Pattern "i"
# or
Write-Output "Hi`nthere".Split("`n") | Select-String -Pattern "i"
仍然有人可以解釋為什么這在這里是相關的,而不是在bash?
uj5u.com熱心網友回復:
所有資訊都在評論中,但讓我總結和補充一下:
PowerShell 的管道是基于物件的,并且Select-String對每個輸入物件進行操作——即使它恰好是單個多行字串物件,例如輸出Write-Output "Hi`nthere"
- 它只是逐行流式傳輸的外部程式的輸出。
因此,您必須將多行字串拆分為單獨的行以匹配它們。
在為最習慣用法-split '\r?\n',因為它承認了Windows格式的CRLF和Unix格式僅LF-換行符:
"Hi`nthere" -split '\r?\n' | Select-String -Pattern "i"
筆記:
我省略
Write-Output了 PowerShell 的隱式輸出行為(有關更多資訊,請參閱此答案的底部部分)。有關
-split '\r?\n'作業原理的更多資訊,請參閱此答案。Select-String不直接輸出匹配的行(字串);相反,它將它們包裝在提供每個匹配元資料的匹配資訊物件中。只獲取匹配的行(字串):- 在PowerShell (Core) 7 中,添加
-Raw開關。 - 在Windows PowerShell 中,
ForEach-Object Line將整個呼叫通過管道傳輸或包裝在(...).Line
- 在PowerShell (Core) 7 中,添加
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/395660.html
