PowerShell实现简单的grep功能
在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]
    }
  }
}总结
相关推荐
  rechanel    2020-11-16  
   taomengxing    2020-09-07  
   wintelx    2020-08-09  
   NBkiller    2020-06-14  
   wandererdl    2020-06-14  
   CARBON    2020-06-11  
   xushxbigbear微信    2020-06-09  
   chenjinlong    2020-06-04  
   eroshn    2020-05-31  
   timegoes    2020-04-12  
   luvzhan    2020-04-12  
   kylinos    2020-03-07  
   季诗筱    2020-03-07  
   神龙    2020-05-11  
   jyj00    2020-05-04  
   LychieFan    2020-05-03  
   csdnyasin    2020-05-01  
   huguang    2020-04-22  
 