在PowerShell中,無法像*nix中一樣使用grep命令,直接對一個目錄下的所有文件進行內容查找,下面的PS腳本針對目錄和文件進行了區分,借用Select-String命令,實現了內容查找,并顯示查找到的文件和匹配內容所在行號。
使用的時候,只需要在shell中,輸入:
"命令所在目錄"/grep.ps1
"需要查找的字符串" "需要查找的路徑"
param($str, $path="./") #輸入參數,默認在當前目錄及其子目錄下查找if([String]::IsNullOrEmpty($str)){ Write-Output "Caution: input string is empty" exit}$path = Resolve-Path $path #獲取絕對路徑if([System.IO.Directory]::Exists($path)){ $subPathList = Get-ChildItem $path -Recurse *.* #獲取所有子目錄 foreach($subPath in $subPathList){ $subPath = $subPath.FullName if([System.IO.Directory]::Exists($subPath)){ Continue } $foundArr = Select-String -path $subPath -Pattern $str foreach($found in $foundArr) { if($found -match "(.+:/d+):") #刪除行號后面的內容 { Write-Output $matches[1] } } }}elseif([system.IO.File]::Exists($path)){ $foundArr = Select-String -path $path -Pattern $str foreach($found in $foundArr) { if($found -match "(.+:/d+):") { Write-Output $matches[1] } }}
總結
以上所述是小編給大家介紹的PowerShell實現簡單的grep功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答