検索
ファイルを探す(find・locate)
名前・サイズ・更新日時などの条件でファイルを探す find と、索引から一瞬で探す locate。
find条件でファイルを探す
名前・大きさ・更新日時などの条件でファイルを探し、見つけたものに処理を行うこともできます。
find [探す場所] [条件...] [処理]| 条件 | 意味 |
|---|---|
-name '*.log' | 名前(大文字小文字を区別しないなら -iname) |
-path '*/test/*' | パス全体で一致 |
-type f / -type d / -type l | ファイル / ディレクトリ / シンボリックリンク |
-size +100M / -size -1k | 100MBより大きい / 1KBより小さい |
-mtime -7 / -mtime +30 | 7日以内に更新 / 30日より前に更新 |
-mmin -10 | 10分以内に更新 |
-newer ref.txt | ref.txt より新しい |
-empty | 空のファイル・ディレクトリ |
-user alice / -perm 644 | 所有者 / 権限 |
-maxdepth N | N階層まで(ほかの条件より前に書く) |
-not / ! / -o | 否定 / 否定 / または |
-prune | そのディレクトリの中は探さない |
| 処理 | 意味 |
|---|---|
-print | 表示する(何も書かなければこれ) |
-print0 | ヌル文字区切りで表示する(xargs -0 向け) |
-delete | 削除する |
-exec cmd {} \; | 見つかったものごとに実行する |
-exec cmd {} + | まとめて1回で実行する(速い) |
-ls | ls -l のように表示する |
$ 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 よりはるかに速いです。ただし作ったばかりのファイルは見つかりません。
$ locate nginx.conf
$ locate -i '*.desktop' | head
$ locate -c '.py' # 件数だけ
$ sudo updatedb # 索引を今すぐ更新するfdシンプルで速い find
Ubuntu には最初から入っていません。 で入れられます。
.gitignore を読み、色付きで表示する find の代わりです。Ubuntu ではコマンド名が fdfind になるので、fd という名前でリンクを張って使います。
$ fd report # 名前に report を含む
$ fd -e go # 拡張子 .go
$ fd -t d src # ディレクトリだけ
$ fd -H '^\.env' # 隠しファイルも
$ fd -e log -x rm # 見つかったものごとに実行