PowerShell實現簡單的grep功能

在PowerShell中,無法像*nix中一樣使用grep命令,直接對一個目錄下的所有文件進行內容查找,下面的PS腳本針對目錄和文件進行了區分,借用Select-String命令,實現了內容查找,並顯示查找到的文件和匹配內容所在行號。
使用的時候,只需要在shell中,輸入:
"命令所在目錄"\grep.ps1 "需要查找的字符串" "需要查找的路徑"

param($str, $path = ".\", $opt = "nl") 
#20171120:增加opt參數,opt爲nl時,不顯示匹配的行號,只顯示匹配的文件路徑;opt爲l時,顯示匹配文件路徑,以及匹配的行號
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($opt -eq "l" -and $found -match ".+?:\d+(?=:)")
            {
                Write-Output $matches[0]
            }
            elseif($found -match ".+?(?=(:\d))")
            {
                Write-Output $matches[0]
                break
            }
        }
    }
}elseif([system.IO.File]::Exists($path)){
    $foundArr = Select-String -path $path -Pattern $str
    foreach($found in $foundArr)
    {
        if($opt -eq "l" -and $found -match ".+?:\d+(?=:)")
        {
            Write-Output $matches[0]
        }
        elseif($found -match ".+?(?=(:\d))")
        {
            Write-Output $matches[0]
            break
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章