ファイル検索コピペ集(PowerShellで文字列・CSSクラス・href=”#”・URL・拡張子で探す、件数を数える)
要点
下の階層まで探すのは Get-ChildItem -Recurse -Include と Select-String の組み合わせ。-SimpleMatch で記号をそのまま検索、-Encoding UTF8 で日本語を正しく読む。件数は Measure-Object。読み取りだけなので安全。
すべて読み取りだけ。基本コマンドの説明は PowerShellのファイル操作の基本(移動・一覧・読む・検索・存在確認・コピー・移動、削除は-WhatIfで確認)。
日本語が文字化けするとき(先に実行)
chcp 65001
[Console]::OutputEncoding = [Text.Encoding]::UTF8
ファイルを読むときは -Encoding UTF8 を付ける。スクリプト(.ps1)自体の文字コードは Windows PowerShell 5.1 で日本語スクリプトが壊れる(UTF-8 BOM が必要)、日本語ファイル名は プロジェクトのファイル名が文字化けしている(UTF-8をCP932として解釈)。
特定の文字列を探す
Select-String -Path .\*.html -Pattern "お問い合わせ" -Encoding UTF8
Get-ChildItem -Recurse -Include *.html,*.php | Select-String -Pattern "お問い合わせ" -Encoding UTF8
結果は「ファイル名:行番号:その行」。ファイル名だけ欲しいとき:
Get-ChildItem -Recurse -Include *.html | Select-String -Pattern "お問い合わせ" -Encoding UTF8 -List | Select-Object -ExpandProperty Path
CSSクラスを探す
Get-ChildItem -Recurse -Include *.html,*.css | Select-String -Pattern "wg-cta" -SimpleMatch -Encoding UTF8
-SimpleMatch は正規表現を使わず文字どおり探す(. や ( を含む語でも安全)。
href="#" を探す
Get-ChildItem -Recurse -Include *.html | Select-String -Pattern 'href="#"' -SimpleMatch -Encoding UTF8
公開前に0件か確認する(公開後検査(公開後チェック)の項目と方法(HTTP・H1・href="#"・実クリック・スマホ390px・横スクロール・既存差分))。
URLを探す
# 特定のドメインへのリンク
Get-ChildItem -Recurse -Include *.html | Select-String -Pattern "http://example.com" -SimpleMatch -Encoding UTF8
# http:// のまま残っているURL(Mixed Contentの候補)
Get-ChildItem -Recurse -Include *.html,*.css | Select-String -Pattern 'http://[^"'' )]+' -Encoding UTF8 | ForEach-Object { $_.Matches.Value } | Sort-Object -Unique
特定の拡張子だけ・ファイル数を数える
Get-ChildItem -Recurse -Filter *.webp # .webp だけ
(Get-ChildItem -Recurse -Filter *.html | Measure-Object).Count # HTMLの数
Get-ChildItem -Recurse -File | Group-Object Extension | Sort-Object Count -Descending # 拡張子ごとの件数
(Get-ChildItem -Recurse -Include *.html | Select-String -Pattern 'href="#"' -SimpleMatch -Encoding UTF8 | Measure-Object).Count # 該当件数
大きいファイルを探す
Get-ChildItem -Recurse -File | Sort-Object Length -Descending | Select-Object -First 10 FullName, @{n='KB';e={[int]($_.Length/1KB)}}
Git Bash の場合
grep -rn 'href="#"' --include=*.html .
grep -rl "wg-cta" --include=*.css .
find . -name "*.html" | wc -l