0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

find/grepコマンド

Last updated at Posted at 2024-12-03

いつも忘れるのでfind/grepコマンドの使い方をメモ
筆者の環境は、Mac/Ubuntu

find

例においてはfindについてはGNU(GNUはPOSIXと結構異なるので移植性を意識するならPOSIXの方がいいらしい)

echo $SHELL # /bin/zsh
type -p find # find is /usr/bin/find (シェル組み込みでない)

filename(つまり、pathの終端)で探す場合

find . -type f -name '*.c'

これだと、ファイル名でしか探せない

pathで探す場合(VSCodeのMacのcmd+p(search files by name)の挙動に近くなる)
最初の ./ と 最後の * が面倒だが、仕方ない

find . -type f -path '*hoge*'

regexでも同じくpathで探すが、こちらはregexなので、regexで書く

find . -type f -regex '.*/hoge/.*'

注意点
なお、シングルクォートで括らないと、SHELLが*を展開しようとして、マッチせずにエラーになる(ならない場合でも意図しない挙動になる)

find . -type f -regex .*/build/.*
zsh: no matches found: .*/build/.*

また、execオプションも使って、各pathに対してコマンドを実行できる(個人的には、execせずに結果を変数に入れたりして新しいコマンドをトップレベルで行いたいと思ってしまう)

find . -name "*.txt" -exec cat {} \;

なお、最後の;は、必須らしい。;が必要で、このセミコロンはシェルの特殊文字なので、エスケープするためにバックスラッシュをいれる。

-ctime 作成日
-mtime 編集日
-atime 最終アクセス日

-1 1日前..現在
-2 2日前..現在
+1 過去永遠..1日前

find <path> -ctime -1

-cmin 作成分
-mmin 編集分
-amin 最終アクセス分

find <path> -cmin -30 # 30分前から現在

grep

grep [オプション] '検索文字列' ファイル
grep -r "search_string" /path/to/directory

オプション
-i: ケースインセンシティブ
-r: 再帰
-E: regex

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?