您好,欢迎来到外链网!
当前位置:外链网 » 站长资讯 » 专业问答 » 文章详细 订阅RssFeed

PowerShell实现简单的grep功能(powershell实现简单程序)

来源:互联网 浏览:103次 时间:2023-04-08

在PowerShell中,无法像*nix中一样使用grep命令,直接对一个内容介绍下的所有文件进行内容查找,下面的PS脚本针对内容介绍和文件进行了区分,借用Select-String命令,实现了内容查找,并显示查找到的文件和匹配内容所在行号。

使用的时候,只需要在shell中,输入:

PowerShell 如何使用PowerShell操作FTP

"命令所在内容介绍"\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 studio破解版 PowerShell Studio下载 v5.5.152.0免费版

总结

<PowerShell 在PowerShell窗口中设置自动补全和智能提示
p>以上所述是小编给大家介绍的PowerShell实现简单的grep功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站长源码网网站的支持!

本文从互联网转载,来源地址:www.downzz.com/linux-shell/170566.html,原作者保留一切权利,若侵权或引用不当,请联系茶猫云(cmy.cn)删除。【茶猫云,优质云服务器提供商】