このエントリーをはてなブックマークに追加


findでファイルのみの一覧、ディレクトリのみの一覧を取得する方法

findコマンドを使用して、指定したディレクトリ配下の

  • ファイルのみの一覧
  • ディレクトリのみの一覧
    を取得する方法を以下に記します。

ファイルのみの一覧を取得する方法

以下の構文で、指定したパス配下のファイルのみの一覧を取得することができます。

find ファイル一覧を取得したいパス -type f

実際に /usr/share 配下のファイル一覧を先頭から10件取得してみます。

$ find /usr/share/ -type f | head -10
/usr/share/nano/javascript.nanorc
/usr/share/nano/rust.nanorc
/usr/share/nano/texinfo.nanorc
/usr/share/nano/java.nanorc
/usr/share/nano/perl.nanorc
/usr/share/nano/nanohelp.nanorc
/usr/share/nano/spec.nanorc
/usr/share/nano/changelog.nanorc
/usr/share/nano/autoconf.nanorc
/usr/share/nano/groff.nanorc

ディレクトリのみの一覧を取得する方法

以下の構文で、指定したパス配下のディレクトリのみの一覧を取得することができます。

find ファイル一覧を取得したいパス -type d

実際に /usr/share 配下のディレクトリ覧を先頭から10件取得してみます。 $ find /usr/share/ -type d | head -10

/usr/share/
/usr/share/nano
/usr/share/xfburn
/usr/share/themes
/usr/share/themes/Numix
/usr/share/themes/Numix/gtk-3.0
/usr/share/themes/Numix/gtk-2.0
/usr/share/themes/Numix/metacity-1
/usr/share/themes/Numix/xfwm4
/usr/share/themes/Numix/gtk-3.20

階層を指定したい場合 -maxdepth

maxdepthオプションを使用すれば、対象とするディレクトリ階層を指定することができます。

  1. 出力をわかりやすくするために、/usr/shareにcd(change directory)しています。
    $ cd /usr/share/
  2. 上記同様に maxdepth を指定せず実行したときの出力です。
    $ find . -type d | head -10
    .
    ./nano
    ./xfburn
    ./themes
    ./themes/Numix
    ./themes/Numix/gtk-3.0
    ./themes/Numix/gtk-2.0
    ./themes/Numix/metacity-1
    ./themes/Numix/xfwm4
    ./themes/Numix/gtk-3.20
  3. 続けて、-maxdepthオプションに1を指定して実行したときの出力です。
    出力を見てわかるとおり、1階層目のディレクトリ一覧が表示されています。
    $ find . -maxdepth 1 -type d | head -10
    .
    ./nano
    ./xfburn
    ./themes
    ./file
    ./liblouisutdml
    ./fontconfig
    ./meld
    ./sensible-utils
    ./appdata
  4. ファイル一覧の場合は、typeオプションをdからfに変更するだけです。

typeオプション

manコマンドでfindを確認すると、以下の記述があります。
本資料では、d directory と f regular file を使用しました。

-type c
   File is of type c:

     b      block (buffered) special

     c      character (unbuffered) special

     d      directory

     p      named pipe (FIFO)

     f      regular file

     l      symbolic  link; this is never true if the -L option or the -follow
            option is in effect, unless the symbolic link is broken.   If  you
            want  to  search  for  symbolic  links  when  -L is in effect, use
            -xtype.

     s      socket

     D      door (Solaris)

以上、findコマンドを使って指定したパス配下のファイル一覧およびディレクトリ一覧を取得する方法でした。



トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2018-12-04 (火) 21:21:18