/Linuxコマンド

検索

ファイルを探す(find・locate)

名前・サイズ・更新日時などの条件でファイルを探す find と、索引から一瞬で探す locate。

find条件でファイルを探す

名前・大きさ・更新日時などの条件でファイルを探し、見つけたものに処理を行うこともできます。

bash
find [探す場所] [条件...] [処理]
条件意味
-name '*.log'名前(大文字小文字を区別しないなら -iname)
-path '*/test/*'パス全体で一致
-type f / -type d / -type lファイル / ディレクトリ / シンボリックリンク
-size +100M / -size -1k100MBより大きい / 1KBより小さい
-mtime -7 / -mtime +307日以内に更新 / 30日より前に更新
-mmin -1010分以内に更新
-newer ref.txtref.txt より新しい
-empty空のファイル・ディレクトリ
-user alice / -perm 644所有者 / 権限
-maxdepth NN階層まで(ほかの条件より前に書く)
-not / ! / -o否定 / 否定 / または
-pruneそのディレクトリの中は探さない
処理意味
-print表示する(何も書かなければこれ)
-print0ヌル文字区切りで表示する(xargs -0 向け)
-delete削除する
-exec cmd {} \;見つかったものごとに実行する
-exec cmd {} +まとめて1回で実行する(速い)
-lsls -l のように表示する
bash
$ find . -name '*.go'
$ find ~ -iname '*report*.pdf'
$ find /var/log -type f -size +50M
$ find . -type f -mtime -1                      # 24時間以内に更新したファイル
$ find . -name node_modules -prune -o -name '*.js' -print   # node_modules を除く
$ find . -type d -empty -delete                 # 空のディレクトリを消す
$ find . -name '*.sh' -exec chmod +x {} +
$ find . -type f -name '*.log' -mtime +30 -print0 | xargs -0 rm -f
$ find . -maxdepth 1 -type f | wc -l            # 直下のファイル数

locate / plocate索引から一瞬で探す

あらかじめ作った索引(1日1回更新)から探すので、find よりはるかに速いです。ただし作ったばかりのファイルは見つかりません。

bash
$ locate nginx.conf
$ locate -i '*.desktop' | head
$ locate -c '.py'          # 件数だけ
$ sudo updatedb            # 索引を今すぐ更新する

fdシンプルで速い find

Ubuntu には最初から入っていません。 で入れられます。

.gitignore を読み、色付きで表示する find の代わりです。Ubuntu ではコマンド名が fdfind になるので、fd という名前でリンクを張って使います。

bash
$ fd report                     # 名前に report を含む
$ fd -e go                      # 拡張子 .go
$ fd -t d src                   # ディレクトリだけ
$ fd -H '^\.env'                # 隠しファイルも
$ fd -e log -x rm               # 見つかったものごとに実行