Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <#
- .Synopsis
- テキストファイルの内容をサブフォルダまで検索して
- コンソール上で読む
- .DESCRIPTION
- searchC: "SearchContent"
- テキストファイルの内容を正規表現でサブディレクトリも含めて検索して
- 連番のインデックスを添えてヒット一覧を表示する
- 出力の最後で入力を受け付ける
- 入力されたインデックスに応じてファイル内容をコンソールに出力
- 文字コードはShiftJISもしくはBOM付きUTF8
- .PARAMETER pattern
- 検索パターン(正規表現対応)
- .EXAMPLE
- searchC ho.*ge
- #>
- function searchC {
- param (
- $pattern,
- $path = "*.txt"
- )
- $i = 0 # インデックス
- $filePathList = New-Object System.Collections.ArrayList # ヒットしたファイルのパス一覧。Arraylistの方が高速らしい
- $hitList = Get-ChildItem $path -Recurse | Select-String -Pattern $pattern -Encoding default
- $hitList = $hitList.Path | Sort-Object -CaseSensitive | Get-Unique
- foreach ($f in $hitList) {
- $i++
- [void]($filePathList.Add($f)) # ArrayListに追加
- $fileName = $f | Split-Path -Leaf
- Write-Host ("$i".PadLeft(4,"0")+" ") -NoNewline -ForegroundColor Yellow
- Write-Host $fileName
- }
- if ($i -gt 0) {
- $inpt = Read-Host "yomu "
- if ($inpt -ne "") {
- [string]$index = $inpt-1
- $openTgt = $filePathList[$index]
- Write-Host $openTgt -ForegroundColor Magenta
- $text = Get-Content -Path $openTgt
- # ヒットした箇所を強調(下記参照)
- foreach ($l in $text) {
- hilightPtn -inputStr $l -searchPtn $pattern -color Green
- }
- }
- }
- }
- <# ====================
- # 第1引数内で第2引数にヒットした箇所をハイライト表示する関数
- function hilightPtn {
- param ([string]$inputStr, [string]$searchPtn, $color = "Yellow")
- while ($inputStr -cmatch $searchPtn) {
- [void]($inputStr -cmatch "(?<pre>.*?)(?<main>$searchPtn)(?<post>.*)") # ヒット箇所とその前後に分ける
- Write-Host $Matches["pre"] -NoNewline -ForegroundColor DarkGray
- Write-Host $Matches["main"] -ForegroundColor $color -NoNewline
- $inputStr = $Matches["post"]
- }
- Write-Host $inputStr -ForegroundColor DarkGray
- }
- ==================== #>
Add Comment
Please, Sign In to add comment