PowerShell实现简单的grep功能

来源:互联网 发布:js获取asp控件的值 编辑:程序博客网 时间:2024/06/05 05:05

在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 $pathif([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        }    }}
原创粉丝点击