find

find -name or -iname

大文字と小文字

findはファイルの大文字と小文字を区別する。 -iname を使うと、大文字と小文字の区別をしない。

準備

1
2
cd "${TMPDIR}sample/shellscript/find/base/1"
touch ./hoge.txt ./sample-Hoge.txt

-name の場合

入力を *hoge.txt とする

1
find . -type f -name '*hoge.txt'

結果

1
./hoge.txt

入力を *Hoge.txt とする

1
find . -type f -name '*Hoge.txt'

結果

1
./sample-Hoge.txt

-iname の場合

1
find . -type f -iname '*Hoge.txt'

結果

1
2
./hoge.txt
./sample-Hoge.txt

Emacsのバックアップファイルやバッファファイルを検索する

例えば次のもの。

  • sample.org~
  • sample.org.undo-tree
  • #sample.org#

sample.org~ や sample.org.undo-tree は ‘*~’ でマッチする。

1
find . -type f -name '*~'

#sample.org# は ‘\#*\#’ でマッチする。

1
find . -type f -name '\#*\#'

find -exec

findは PRIMARIES という入力を受け付ける。この中に -exec がある。 -exec はfindの検索結果に対して実行したいコマンドを指定できる。 findの検索結果をパイプでxargsに渡す方法もあるが -exec でほとんどの場合は事足りるだろう。

使用例 - echo

準備

1
2
cd "${TMPDIR}sample/shellscript/find/exec/1"
touch ./hoge.txt ./foo.txt ./bar.txt

1
find . -type f -name '*.txt' -exec echo {} \; # find . -type f -name '*.txt' と同じ

結果

1
2
3
./hoge.txt
./foo.txt
./bar.txt

1
find . -type f -name '*.txt' -exec echo {} +

結果

1
./hoge.txt ./foo.txt ./bar.txt

検索条件に合致するファイルを一度に削除する

1
find . -type f -name '*.txt' -exec rm {} +