シェルでfindコマンドの実行結果を `ls -l` のようなフォーマットで出力する
はじめに
find
コマンドを実行するとファイルの一覧が出力されます。
例えば、以下は /etc
ディレクトリの中から、拡張子 sh
を持つファイルを検索し一覧表示した結果となります。
$ find /etc -name '*.sh'
/etc/bash_completion.d/mercurial.sh
/etc/profile.d/colorgrep.sh
/etc/profile.d/colorls.sh
/etc/profile.d/less.sh
ちなみに一番最初に見つかったファイルを ls -l
コマンドの引数として実行すると、以下のようにファイルのパーミッションや所有者、グループ、サイズが確認できます。
$ ls -l /etc/bash_completion.d/mercurial.sh
-rw-r--r-- 1 root root 11736 Apr 1 2020 /etc/bash_completion.d/mercurial.sh
find
の実行結果を ls -l
のようなフォーマットで出力する方法はないでしょうか?
検証環境
$ uname -moi
x86_64 x86_64 GNU/Linux
$ head -n 2 /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
$ bash -version | head -n 1
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
方法1 : -ls
オプションを使用する
find
コマンドには、 -ls
オプションというものがあります。
-ls
オプションを付与すると、 find
の実行結果が -ls
のようになります。 ( 厳密には ls -dils
の実行結果と同様の表示のされ方となります。 )
実際に実行してみます。
$ find /etc -name '*.sh' -ls
4726226 12 -rw-r--r-- 1 root root 11736 Apr 1 2020 /etc/bash_completion.d/mercurial.sh
8131757 4 -rw-r--r-- 1 root root 201 Mar 24 2017 /etc/profile.d/colorgrep.sh
8131759 4 -rw-r--r-- 1 root root 1606 Aug 6 2019 /etc/profile.d/colorls.sh
4599183 4 -rw-r--r-- 1 root root 121 Jul 30 2015 /etc/profile.d/less.sh
左から 1列目が inode と呼ばれるもの、2列名が ブロック数 と呼ばれるものですが、それ以外は ls -l
の実行結果と同様です。
方法2 : xargs
を使用する
Busybox のような少し変わったDockerOS環境の場合には、 find
の -ls
オプションが利用できません。
そんなときには xargs
コマンドを使うことで実現できます。
$ find /etc -name '*.sh' | xargs ls -l
-rw-r--r-- 1 root root 11736 Apr 1 2020 /etc/bash_completion.d/mercurial.sh
-rw-r--r-- 1 root root 201 Mar 24 2017 /etc/profile.d/colorgrep.sh
-rw-r--r-- 1 root root 1606 Aug 6 2019 /etc/profile.d/colorls.sh
-rw-r--r-- 1 root root 150 Aug 7 23:54 /etc/profile.d/less.sh
find -ls
のフォーマットに完全に合わせたい場合は以下のように ls
コマンドに指定するオプションを -dils
とします。
$ find /etc -name '*.sh' | xargs ls -dils
4726226 12 -rw-r--r-- 1 root root 11736 Apr 1 2020 /etc/bash_completion.d/mercurial.sh
8131757 4 -rw-r--r-- 1 root root 201 Mar 24 2017 /etc/profile.d/colorgrep.sh
8131759 4 -rw-r--r-- 1 root root 1606 Aug 6 2019 /etc/profile.d/colorls.sh
4599183 4 -rw-r--r-- 1 root root 150 Aug 7 23:54 /etc/profile.d/less.sh
ひとこと
所有者やパーミッションも含めて横串に確認したい場合に便利です。
ディスカッション
コメント一覧
コメントが上手くできない問題を修正しました!