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 } }}
阅读全文
0 0
- PowerShell实现简单的grep功能
- PowerShell 下的grep
- grep的功能
- 通过Java实现Linux系统下grep指令的功能
- Powershell socket的简单应用
- 限次版功能的简单实现
- 实现简单的notepad功能
- 简单的实现涂鸦功能
- 实现简单功能的通讯录
- 简单的实现涂鸦功能
- 简单的实现考试功能
- 截图功能的简单实现
- 简单扫一扫功能的实现
- 简单分页功能的实现
- 简单计算器的功能实现
- 实现简单的天气预报功能
- 管道实现ls 与grep功能
- PowerShell的开源实现
- 使用layui背景花屏
- [HDU]2829 Lawrence 斜率优化
- 最终解决Mybatis多表联合查询中字段名重复导致的各路问题
- 使用pip安装包
- 朴素贝叶斯分类器——理论
- PowerShell实现简单的grep功能
- xml 读写
- jQuery length 和 size()区别
- Java 标准 I/O 流编程一览笔录
- 7-24 树种统计(25 分)
- -bash: ls: command not found 或ifconfig ,su 等命令不能使用
- TCP分段与IP分片
- Spark算子总结(带案例)
- C++ primer——函数学习