findコマンドの使い方

findコマンドはファイルやディレクトリを見つけるunixのコマンド。

基本的な使い方

find [パス] [オプション]


~/Downloads以下のファイル、ディレクトリを一覧する

find ~/Downloads

 

オプション① (ファイルを指定)

ファイル名を指定する: -name/iname

  • -inameにすると大文字と小文字を区別しない。

~/Downloads以下のテキストファイルを一覧する

find ~/Downloads -name "*.txt"

~/Downloads以下のテキストファイ以外を一覧する

find ~/Downloads ! -name "*.txt"

 

ファイルタイプを指定する: -type

~/Downloads以下のディレクトリを一覧する

find ~/Downloads -type d

~/Downloads以下のファイルを一覧する

find ~/Downloads -type f

 

オプションをORでつなぐ: -o

~/Downloads以下のテキストファイルとhtmlファイルを一覧する

find ~/Downloads -name "*.txt" -o -name "*.html"

優先順位をつける場合は\( \)で囲む

find ~/Downloads \( -name "*.txt" -o -name "*.html" \) -type f

 

ユーザやグループを指定する: -user/-group

~/Downloads以下でgackelのファイルを一覧する

find ~/Downloads -user gackel

 

パーミッションを指定する: -perm

~/Downloads以下でパーミッションが777のファイルを一覧する

find ~/Downloads -perm 777

 

検索する深さを指定する: -maxdepth

~/Downloads以下で3階層目まで検索する

find ~/Downloads -maxdepth 3

 

日付を指定する: -atime/-mtime/-ctime

  • -atime: 最終アクセス時刻[access time]
  • -mtime: 最終変更時刻[modify time]
  • -ctime: 最終ステータス変更時刻[change time]
  • 指定した数字(n)x24時間より前だったら(-n)、後だったら(+n)

~/Downloads以下で直近24時間以内に変更されたファイルを一覧する

find ~/Downloads -mtime -1

~/Downloads以下で24時間以前に変更されたファイルを一覧する

find ~/Downloads -mtime +1


 

オプション② (指定したファイルに対してコマンドを実行)

条件に合致したファイルにコマンドを実行: -exec/-ls/-print

  • find [パス] -exec [コマンド] {} \;
    • \; までの文字列がコマンドとして認識され、{} が find での検索にヒットしたファイル名やディレクトリ名に置き換えられる。

~/Downloads以下のファイルをすべて削除する

find ~/Downloads -exec rm -rf {} \;

  • find [パス] -ls
    • ファイルやディレクトリの詳細を一覧表示する

  • find [パス] -print
    • 検索結果を一覧表示
    • -exec/-ls/-print を省略した場合は-printを指定したことになる

つまり以下の2つは等価

find ~/Downloads 
find ~/Downloads -print

~/Downloads以下でhogeを含む部分をgrepし、ファイル名をprintする

find ~/Downloads -exec grep hoge {} \; -print