Home > Windows にまつわる e.t.c.

PowerShell 版 grep


Windows には標準で grep コマンドがありません

似たような事ができる PowerShell コマンドレットで Select-String がありますが、ファイルの再帰検索指定が出来ないとか、意外と使い勝手が悪いので、Select-String をラッピングした grep 関数にしちゃいました

#########################################
# grep by PowerShell
#########################################
function grep( $MatchPattern, $FilePattern, [switch]$Recurse ){
    if($Recurse){
        [array]$Files = Get-ChildItem $FilePattern -Recurse
    }
    else{
        [array]$Files = Get-ChildItem $FilePattern
    }

    foreach($File in $Files){
        $FileName = $File.FullName
        Select-String -Path $FileName -Pattern $MatchPattern -CaseSensitive
    }
}

 

■ 使い方

grep 正規表現 ファイルパターン -Recurse

 

■ 実行例

grep 18[0-9] c:\temp\*.txt -Recurse

 

■ 動作確認

Windows PowerShell 5.1
PowerShell 7.1.3(Windows)

 

インストーラー込みで GitHub で公開していますので、ご入用の方はどうぞ

https://github.com/MuraAtVwnet/grep

git@github.com:MuraAtVwnet/grep.git

 

back.gif (1980 バイト)

home.gif (1907 バイト)

Copyright © MURA All rights reserved.