* Select-Stringでテキスト検索 [#v703db63]

** 検索の指定方法 [#q0c1b767]

*** ファイルのテキスト検索 [#w8f2ab67]

 Select-String -Path "*.txt" -Pattern "hello"

Patternで指定する文字列はデフォルトで正規表現が使える。

*** エイリアス・PathとPatternの省略 [#q24a467e]

 sls "hello" *.txt

*** OR検索 [#vcaf22fe]

 sls "hello", "world" *.txt

"hello"または"world"がある行にマッチする。

*** NOT検索 [#d6715519]

 sls -Path *.txt -NotMatch -Pattern "hello","world" 

"hello"も"world"もない行にマッチする。

*** AND検索 [#y7669726]
 sls "hello" *.txt | sls "world"
 または
 Get-Content *.txt | Where-Object { $_ -match "hello" -and $_ -match "world" }

"hello"と"world"がある行にマッチする。

*** -AllMatchesオプション 各行で複数の一致を検索 [#p64ab945]
"hello, hello"と書かれたtest.txtがあるとする。
 PS> gc test.txt
 hello, hello

AllMachesオプションなしでは、
 PS> $ret = sls "hello" test.txt
 PS> $ret.Matches
 Groups   : {hello}
 Success  : True
 Captures : {hello}
 Index    : 0
 Length   : 5
 Value    : hello

1文字目(Index:0)のhelloだけキャプチャーされる。AllMachesオプションありでは
 PS> $ret = sls "hello" test.txt -AllMatches
 Groups   : {hello}
 Success  : True
  Captures : {hello}
 Index    : 0
 Length   : 5
 Value    : hello
 
 Groups   : {hello}
 Success  : True
 Captures : {hello}
 Index    : 6
 Length   : 5
 Value    : hello
1文字目に加えて、5文字目(Index:6)のhelloもキャプチャーされる。

** 検索結果の加工 [#naa22ff5]
*** マッチしたファイル名を取得 [#x5c30e35]
 sls "hello" *.txt | Select-Object filename | Get-Unique -AsString
- Select-Objectの結果はMatchInfoオブジェクトなので、Get-UniqueにはAsStringオプションを付けて文字列として解釈するようにする。


** 参考 [#tbce4165]
- https://technet.microsoft.com/ja-JP/library/dd315403.aspx


トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS