ささやかな日々記

日々過ごす中で感じたことや培ったことが誰かの役に立てられたらと思うSEの雑記

PowerShell grep的なコマンドレット

PowerShellGrep的なことをしてくれるコマンドレットについて書いていきます。

コマンドレット「Select-String」で指定した文字列を検索することが出来ます。

まずはHelpでどういうものか確認します。細かいところは割愛。

 

PS C:\> Get-Help Select-String

名前
Select-String

概要
文字列とファイルのテキストを検索します。


構文
Select-String [-Path] <string> [-Pattern] <string> [-AllMatches] [-CaseSensitive] [-Context <Int32>] [-Encodi
ng <string>] [-Exclude <string
>] [-Include <string>] [-List] [-NotMatch] [-Quiet] [-SimpleMatch] [<CommonParame
ters>]

Select-String -InputObject <psobject> [-Pattern] <string> [-AllMatches] [-CaseSensitive] [-Context <Int32>] [-E
ncoding <string>] [-Exclude <string
>] [-Include <string[]>] [-List] [-NotMatch] [-Quiet] [-SimpleMatch] [<CommonP
arameters>]

・・・ 

 使い方的にはLinuxGrepみたいに使えるようです。

では使ってみます。対象は以下のファイルがおいてあり、ファイルの中身はファイル名と同じ文字列が記録されています。(拡張子を除く)

PS C:\work> dir


ディレクトリ: C:\work


Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2019/04/19 19:37 3 aaa.txt
-a--- 2019/04/19 19:38 5 abc.txt
-a--- 2019/04/19 19:39 2 bc
-a--- 2019/04/19 19:38 1 c.txt

 

まずは「a」という文字列がどのファイルにあるかを検索。

PS C:\work> Select-String * -Pattern a

aaa.txt:1:aaa
abc.txt:1:abc 

 

次に「c」という文字列がどのファイルにあるかを検索。

PS C:\work> Select-String * -Pattern c

abc.txt:1:abc
bc:1:bc
c.txt:1:c

 次は「c」という文字列がどのファイル(拡張子がtxt)にあるかを検索。

PS C:\work> Select-String *.txt -Pattern c

abc.txt:1:abc
c.txt:1:c

 次は「c」という文字列が含まれないファイルの検索。

PS C:\work> Select-String *.* -Pattern c -NotMatch

aaa.txt:1:aaa