在PowerShell中,無法像*nix中一樣使用grep命令,直接對一個目錄下的所有文件進行內(nèi)容查找,下面的PS腳本針對目錄和文件進行了區(qū)分,借用Select-String命令,實現(xiàn)了內(nèi)容查找,并顯示查找到的文件和匹配內(nèi)容所在行號。
使用的時候,只需要在shell中,輸入:
"命令所在目錄"\grep.ps1
"需要查找的字符串" "需要查找的路徑"
param($str, $path=".\") #輸入?yún)?shù),默認在當(dāng)前目錄及其子目錄下查找 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+):") #刪除行號后面的內(nèi)容 { 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] } } }
總結(jié)
以上所述是小編給大家介紹的PowerShell實現(xiàn)簡單的grep功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
標(biāo)簽:臨沂 烏蘭察布 連云港 贛州 海北 昌都 撫州 廣東
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PowerShell實現(xiàn)簡單的grep功能》,本文關(guān)鍵詞 PowerShell,實現(xiàn),簡單,的,grep,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。