在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功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
您可能感兴趣的文章:
- PowerShell小技巧之实现文件下载(类wget)
- Powershell小技巧之使用Get-ChildItem得到指定扩展名文件
- PowerShell中使用Get-Alias命令获取cmdlet别名例子
- PowerShell中使用Get-Date获取日期时间并格式化输出的例子
- PowerShell中使用Get-EventLog读取、筛选系统日志的例子
- PowerShell中使用Out-String命令把对象转换成字符串输出的例子
- PowerShell中使用Get-ChildItem命令读取目录、文件列表使用例子和小技巧