我正在尋找 json 檔案中的搜索字串:
> type .\input.json
[
{"name": "moish"},
{"name": "oren"}
]
> type .\input.json | findstr /n /l "\`"name\`": \`"or"
2: {"name": "moish"},
3: {"name": "oren"}
怎么moish找到入口?我錯過了什么?
uj5u.com熱心網友回復:
通過加倍來轉義文字引號:
type input.json |findstr /n /l """name"": ""or"
...或使用單引號來限定搜索詞:
type input.json |findstr /n /l '"name": "or'
.... 或者也許使用本機 PowerShell cmdletSelect-String而不是findstr:
Select-String -LiteralPath input.json -Pattern '"name": "or'
uj5u.com熱心網友回復:
在/c:您的搜索字串之前添加,以便findstr將其視為要搜索的單個字串:
Get-Content .\input.json | findstr /n /l /c:"\`"name\`": \`"or" # Note the /c:
請注意使用Get-Contentcmdlet 逐行讀取檔案,這type是 PowerShell 中的內置別名。
筆記:
默認情況下,如果搜索字串包含空格,則
findstr搜索出現的任何空格分隔的單詞,即"name"or"or,從而使兩行都匹配。/c:表示應該搜索整個字串/l的信號(作為正則運算式,默認情況下,或作為文字字串,使用)除了缺少的
/c:,您的搜索字串是正確的,但您可以通過使用逐字(單引號)字串 ('...')來簡化:... | findstr /n /l /c:'\"name\": \"or'- 可悲的是,嵌入字符的附加- 轉義。 無論如何都是必需的,至少到 PowerShell 7.2.x,即使它不應該是必需的。
\"- 這是由于 PowerShell 如何將帶有嵌入式雙引號的引數傳遞給外部程式的一個長期存在的錯誤;一個 - 可能選擇加入 - 修復可能即將到來 - 看到這個答案。
PowerShell 替代方案Select-String:
如Mathias R. Jessen 的回答所示,您也可以使用Select-Stringcmdlet,它是更強大的 PowerShell 對應物findstr.exe,尤其是為了避免參考頭痛(見上文)和潛在的字符編碼問題。
Like
findstr.exe,默認Select-String使用正則運算式;用于-SimpleMatch選擇文字匹配。不像
findstre.exe,默認情況下不Select-String區分大小寫(就像 PowerShell 通常一樣)。用于-CaseSensitive使匹配區分大小寫。Select-String將匹配行包裝在包含有關每個匹配項的元資料的物件中;如果您只對行文本感興趣,請-Raw在PowerShell (Core) 7ForEach-Object Line中使用,或在Windows PowerShell中使用管道。雖然通過管道從檔案中讀取管道行
Get-Content,但它比通過其引數將檔案路徑作為引數直接傳遞給(您也可以將使用它獲得的檔案資訊物件通過管道傳遞給它)要慢得多。Select-String-LiteralPathGet-ChildItem- 這具有額外的優勢,即匹配行的顯示表示包括檔案名和行號(見下文)。
findstr.exe因此,您的(更正后的)呼叫的等價物是:
Select-String -LiteralPath .\input.json -CaseSensitive -SimpleMatch -Pattern '"name": "or'
# Alternative:
Get-ChildItem .\input.json |
Select-String -CaseSensitive -SimpleMatch -Pattern '"name": "or'
您將在控制臺中獲得以下輸出(注意由檔案名和行號組成的輸出行前綴):
input.json:3: {"name": "oren"}
請注意,這是為匹配行發出的型別物件[Microsoft.PowerShell.Commands.MatchInfo]的顯示表示。Select-String
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/507624.html
上一篇:Powershell命令Compress-Archive非常慢
下一篇:MicrosoftGraph中缺少UsersPermissionToUserConsentToAppEnabled是否有任何解決方法?
