我正在寻找PowerShell等价于grep——file=filename。如果你不知道grep, filename是一个文本文件,其中每一行都有一个你想要匹配的正则表达式模式。
也许我遗漏了一些明显的东西,但是Select-String似乎没有这个选项。
我正在寻找PowerShell等价于grep——file=filename。如果你不知道grep, filename是一个文本文件,其中每一行都有一个你想要匹配的正则表达式模式。
也许我遗漏了一些明显的东西,但是Select-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
其他回答
但是select-String似乎没有这个选项。
正确的。PowerShell不是*nix shell工具集的克隆。
然而,自己建造这样的东西并不难:
$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
}
我有同样的问题,试图找到文件中的文本与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"
我不熟悉grep,但选择字符串你可以做:
Get-ChildItem filename.txt | Select-String -Pattern <regexPattern>
你也可以使用Get-Content:
(Get-Content filename.txt) -match 'pattern'
Select-String中的-Pattern参数支持模式数组。所以你要找的是
Get-Content .\doc.txt | Select-String -Pattern (Get-Content .\regex.txt)
它通过使用regex.txt中的每个regex(每行一个)来搜索文本文件doc.txt
也许?
[regex]$regex = (get-content <regex file> |
foreach {
'(?:{0})' -f $_
}) -join '|'
Get-Content <filespec> -ReadCount 10000 |
foreach {
if ($_ -match $regex)
{
$true
break
}
}