我正在寻找PowerShell等价于grep——file=filename。如果你不知道grep, filename是一个文本文件,其中每一行都有一个你想要匹配的正则表达式模式。

也许我遗漏了一些明显的东西,但是Select-String似乎没有这个选项。


当前回答

也许?

[regex]$regex = (get-content <regex file> |
foreach {
          '(?:{0})' -f $_
        }) -join '|'

Get-Content <filespec> -ReadCount 10000 |
 foreach {
           if ($_ -match $regex)
             {
              $true
              break
             }
         }

其他回答

我有同样的问题,试图找到文件中的文本与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"
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 /?

所以我在这个链接上找到了一个很好的答案: 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

也许?

[regex]$regex = (get-content <regex file> |
foreach {
          '(?:{0})' -f $_
        }) -join '|'

Get-Content <filespec> -ReadCount 10000 |
 foreach {
           if ($_ -match $regex)
             {
              $true
              break
             }
         }

我不熟悉grep,但选择字符串你可以做:

Get-ChildItem filename.txt | Select-String -Pattern <regexPattern>

你也可以使用Get-Content:

(Get-Content filename.txt) -match 'pattern'