Linux findコマンド入門
条件を指定してファイルを検索する
findコマンドでファイル名・サイズ・日時・権限など多彩な条件でファイルを検索する方法を解説します。
こんな人向けの記事です
- ファイルやディレクトリを条件付きで検索したい方
- 古いファイルの一括削除やクリーンアップを行いたい方
- 検索結果に対してコマンドを実行する方法を知りたい方
Step 1findコマンドの基本
findコマンドはディレクトリツリーを再帰的に検索し、指定した条件に一致するファイルやディレクトリを見つけるコマンドです。
ターミナル
# 基本構文
find [検索開始ディレクトリ] [条件] [アクション]
# ファイル名で検索
find . -name "filename.txt"
find /home -name "*.log"
# 大文字小文字を区別しない検索
find . -iname "README*"
# ファイルタイプで検索
find . -type f # ファイルのみ
find . -type d # ディレクトリのみ
find . -type l # シンボリックリンクのみ
# 深度を制限
find . -maxdepth 2 -name "*.txt"
基本的な条件: -name=ファイル名(大文字小文字区別)、-iname=ファイル名(区別なし)、-type f=ファイル、-type d=ディレクトリ
Step 2サイズと時間で検索する
ファイルサイズや更新日時を条件にした検索方法を説明します。
ターミナル
# サイズによる検索
find . -size +100M # 100MB以上のファイル
find . -size -1k # 1KB未満のファイル
find . -type f -empty # 空のファイル
# 更新日時による検索
find . -mtime -7 # 7日以内に変更
find . -mtime +30 # 30日以前に変更
find . -mmin -60 # 60分以内に変更
# 日付を指定して検索
find . -newermt "2024-01-01" # 2024年1月1日以降に変更
# アクセス時間で検索
find . -atime -1 # 1日以内にアクセス
| 条件 | 説明 |
|---|---|
-size +100M | 100MB以上 |
-size -1k | 1KB未満 |
-mtime -7 | 7日以内に変更 |
-mtime +30 | 30日以前に変更 |
-mmin -60 | 60分以内に変更 |
-empty | 空のファイル/ディレクトリ |
Step 3権限と所有者で検索する
ファイルの権限や所有者を条件とした検索方法を説明します。
ターミナル
# 権限による検索
find . -perm 644 # ちょうど644の権限
find . -perm -644 # 644以上の権限
find . -type f -executable # 実行可能ファイル
# 所有者・グループによる検索
find . -user root # rootが所有
find . -group wheel # wheelグループが所有
find . -user $USER # 現在のユーザーが所有
# セキュリティチェック
find /tmp -type f -perm -002 # 他人が書き込み可能なファイル
find /usr/bin -type f -perm -4000 # setuidバイナリ
注意: -perm 644は「ちょうど644」、-perm -644は「644以上」、-perm /644は「いずれかのビットが設定」という意味です。混同しないよう注意しましょう。
Step 4複合条件とアクション
複数の条件を組み合わせた検索と、見つかったファイルに対するアクション実行について説明します。
ターミナル
# 論理演算子
find . -name "*.log" -and -size +1M # ANDで条件結合
find . -name "*.txt" -o -name "*.md" # ORで条件結合
find . -not -name "*.tmp" # NOTで条件反転
# アクション: コマンド実行
find . -name "*.log" -exec ls -lh {} +
find . -name "*.tmp" -exec rm {} \;
find . -name "*.py" -exec grep -l "import" {} +
# 削除アクション
find . -name "*.bak" -delete
# 確認付き実行
find . -name "*.tmp" -ok rm {} \;
# 特定ディレクトリを除外
find . -path "./node_modules" -prune -o -name "*.js" -print
| アクション | 説明 |
|---|---|
-print | ファイル名表示(デフォルト) |
-ls | 詳細表示(ls -l形式) |
-exec CMD {} \; | 各ファイルにコマンド実行 |
-exec CMD {} + | まとめてコマンド実行(高速) |
-delete | ファイル削除 |
-ok CMD {} \; | 確認付きコマンド実行 |
Step 5実践的な使用例
システム管理、開発、メンテナンスでよく使用されるfindコマンドの実践例を紹介します。
ターミナル
# 古いファイルのクリーンアップ
find /var/log -name "*.log" -mtime +30 -delete
find /tmp -type f -atime +7 -delete
# 大容量ファイルの検索
find / -type f -size +1G 2>/dev/null | head -10
# プロジェクトのコード検索
find . -name "*.py" -exec grep -l "TODO" {} +
# macOSのメタデータファイル削除
find . -name ".DS_Store" -delete
# ファイル数カウント
find . -type f | wc -l
find . -type f -name "*.py" | wc -l
# 権限エラーを非表示にして検索
find /etc -name "*.conf" 2>/dev/null
性能最適化のコツ: -maxdepthで深度制限、-pruneで不要ディレクトリをスキップ、-quitで最初のマッチで停止できます。