我正在寻找与
grep --file=filename
等效的 PowerShell。如果您不知道grep
,文件名是一个文本文件,其中每一行都有一个您想要匹配的正则表达式模式。
也许我错过了一些明显的东西,但是
Select-String
似乎没有这个选项。
-Pattern
中的Select-String
参数支持一系列模式。所以您要找的是:
Get-Content .\doc.txt | Select-String -Pattern (Get-Content .\regex.txt)
这通过使用
doc.txt
中的每个正则表达式(每行一个)来搜索文本文件
regex.txt
PS) new-alias grep findstr
PS) C:\WINDOWS> ls | grep -I -N exe
105:-a--- 2006-11-02 13:34 49680 twunk_16.exe
106:-a--- 2006-11-02 13:34 31232 twunk_32.exe
109:-a--- 2006-09-18 23:43 256192 winhelp.exe
110:-a--- 2006-11-02 10:45 9216 winhlp32.exe
PS) grep /?
我不熟悉 grep 但使用 Select-String 你可以这样做:
Get-ChildItem filename.txt | Select-String -Pattern <regexPattern>
您也可以使用 Get-Content 来做到这一点:
(Get-Content filename.txt) -match 'pattern'
我在尝试使用 powershell 在文件中查找文本时遇到了同样的问题。我使用了以下方法 - 尽可能接近 Linux 环境。
希望这对某人有帮助:
PowerShell:
PS) new-alias grep findstr
PS) ls -r *.txt | cat | grep "some random string"
说明:
ls - lists all files
-r - recursively (in all files and folders and subfolders)
*.txt - only .txt files
| - pipe the (ls) results to next command (cat)
cat - show contents of files comming from (ls)
| - pipe the (cat) results to next command (grep)
grep - search contents from (cat) for "some random string" (alias to findstr)
是的,这也有效:
PS) ls -r *.txt | cat | findstr "some random string"
所以我在此链接中找到了一个很好的答案: https://www.thomasmaurer.ch/2011/03/powershell-search-for-string-or-grep-for-powershell/
但本质上是:
Select-String -Path "C:\file\Path\*.txt" -Pattern "^Enter REGEX Here$"
这在 PowerShell 的一行中提供了目录文件搜索(*或者您可以只指定一个文件)和文件内容搜索,与 grep 非常相似。输出将类似于:
doc.txt:31: Enter REGEX Here
HelloWorld.txt:13: Enter REGEX Here
当你想在管道输出中使用grep时,我通过PowerShell的“过滤器”和“别名”找到了一种可能的方法(grep文件应该类似):
首先定义一个过滤器:
filter Filter-Object ([string]$pattern) {
Out-String -InputObject $_ -Stream | Select-String -Pattern "$pattern"
}
然后定义别名:
New-Alias -Name grep -Value Filter-Object
最后,将之前的过滤器和别名放入您的个人资料中:
$Home[我的]Documents\PowerShell\Microsoft.PowerShell_profile.ps1
重新启动你的PS,这样你就可以使用它了:
别名 | grep 'grep'
参考文献
这个问题已经有了答案,但我只想补充一点,在 Windows 中,有适用于 Linux 的 Windows 子系统 WSL。
例如,如果您想检查是否有名为 Elasicsearch 且处于状态 running 的服务,您可以在 powershell 中执行类似以下代码片段的操作
net start | grep Elasticsearch
但是select-String好像没有这个选项
正确。 PowerShell 不是 *nix shells 工具集的克隆。
然而,自己构建类似的东西并不难:
$regexes = Get-Content RegexFile.txt |
Foreach-Object { new-object System.Text.RegularExpressions.Regex $_ }
$fileList | Get-Content | Where-Object {
foreach ($r in $regexes) {
if ($r.IsMatch($_)) {
$true
break
}
}
$false
}
也许?
[regex]$regex = (get-content <regex file> |
foreach {
'(?:{0})' -f $_
}) -join '|'
Get-Content <filespec> -ReadCount 10000 |
foreach {
if ($_ -match $regex)
{
$true
break
}
}
遇到可能感兴趣的内容:“mlocate”(yum install mlocate)。要使用,请输入“locate [file]”。