Guest User

Untitled

a guest
Jan 17th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. <#
  2. .Synopsis
  3. テキストファイルの内容をサブフォルダまで検索して
  4. コンソール上で読む
  5.  
  6. .DESCRIPTION
  7. searchC: "SearchContent"
  8. テキストファイルの内容を正規表現でサブディレクトリも含めて検索して
  9. 連番のインデックスを添えてヒット一覧を表示する
  10.  
  11. 出力の最後で入力を受け付ける
  12. 入力されたインデックスに応じてファイル内容をコンソールに出力
  13. 文字コードはShiftJISもしくはBOM付きUTF8
  14.  
  15. .PARAMETER pattern
  16. 検索パターン(正規表現対応)
  17.  
  18. .EXAMPLE
  19. searchC ho.*ge
  20.  
  21. #>
  22. function searchC {
  23. param (
  24. $pattern,
  25. $path = "*.txt"
  26. )
  27.  
  28. $i = 0 # インデックス
  29. $filePathList = New-Object System.Collections.ArrayList # ヒットしたファイルのパス一覧。Arraylistの方が高速らしい
  30. $hitList = Get-ChildItem $path -Recurse | Select-String -Pattern $pattern -Encoding default
  31. $hitList = $hitList.Path | Sort-Object -CaseSensitive | Get-Unique
  32.  
  33. foreach ($f in $hitList) {
  34. $i++
  35. [void]($filePathList.Add($f)) # ArrayListに追加
  36.  
  37. $fileName = $f | Split-Path -Leaf
  38. Write-Host ("$i".PadLeft(4,"0")+" ") -NoNewline -ForegroundColor Yellow
  39. Write-Host $fileName
  40.  
  41. }
  42.  
  43. if ($i -gt 0) {
  44. $inpt = Read-Host "yomu "
  45.  
  46. if ($inpt -ne "") {
  47. [string]$index = $inpt-1
  48. $openTgt = $filePathList[$index]
  49. Write-Host $openTgt -ForegroundColor Magenta
  50. $text = Get-Content -Path $openTgt
  51.  
  52. # ヒットした箇所を強調(下記参照)
  53. foreach ($l in $text) {
  54. hilightPtn -inputStr $l -searchPtn $pattern -color Green
  55. }
  56. }
  57. }
  58. }
  59. <# ====================
  60. # 第1引数内で第2引数にヒットした箇所をハイライト表示する関数
  61.  
  62. function hilightPtn {
  63. param ([string]$inputStr, [string]$searchPtn, $color = "Yellow")
  64.  
  65. while ($inputStr -cmatch $searchPtn) {
  66. [void]($inputStr -cmatch "(?<pre>.*?)(?<main>$searchPtn)(?<post>.*)") # ヒット箇所とその前後に分ける
  67. Write-Host $Matches["pre"] -NoNewline -ForegroundColor DarkGray
  68. Write-Host $Matches["main"] -ForegroundColor $color -NoNewline
  69. $inputStr = $Matches["post"]
  70. }
  71. Write-Host $inputStr -ForegroundColor DarkGray
  72. }
  73. ==================== #>
Add Comment
Please, Sign In to add comment