当前位置: 移动技术网 > 网络运营>服务器>Linux > PowerShell实现简单的grep功能

PowerShell实现简单的grep功能

2017年12月01日  | 移动技术网网络运营  | 我要评论
在powershell中,无法像*nix中一样使用grep命令,直接对一个目录下的所有文件进行内容查找,下面的ps脚本针对目录和文件进行了区分,借用select-strin

在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功能,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网