lsコマンドでディレクトリのみ、ファイルのみを表示する方法

目次

スポンサードリンク

Linuxのlsコマンドではファイルやディレクトリを一覧表示することができます。表示結果の内、ディレクトリのみ表示する方法、ファイルのみ表示する方法を解説します。

ディレクトリのみ表示する方法

例として以下のようなディレクトリ、ファイルがあるとします。lsコマンドに -l オプションを指定することで先頭にファイルのタイプや権限が表示されます。ディレクトリは各行の先頭が d で始まります。

[root@hostname ~]# cd /opt/apache-tomcat-8.5.34/
[root@hostname apache-tomcat-8.5.34]# ls -l
total 240
drwxr-x--- 2 tomcat tomcat  4096 Oct 15  2018 bin
-rw-r----- 1 tomcat tomcat 19539 Sep  5  2018 BUILDING.txt
drwx------ 3 tomcat tomcat  4096 Oct 15  2018 conf
-rw-r----- 1 tomcat tomcat  6090 Sep  5  2018 CONTRIBUTING.md
drwxr-x--- 2 tomcat tomcat  4096 Oct 15  2018 lib
-rw-r----- 1 tomcat tomcat 57092 Sep  5  2018 LICENSE
drwxr-x--- 2 tomcat tomcat 98304 Apr 21 22:27 logs
-rw-r----- 1 tomcat tomcat  1726 Sep  5  2018 NOTICE
-rw-r----- 1 tomcat tomcat  3255 Sep  5  2018 README.md
-rw-r----- 1 tomcat tomcat  7142 Sep  5  2018 RELEASE-NOTES
-rw-r----- 1 tomcat tomcat 16262 Sep  5  2018 RUNNING.txt
drwxr-x--- 2 tomcat tomcat  4096 Oct 15  2018 temp
drwxr-x--- 7 tomcat tomcat  4096 Oct 15  2018 webapps
drwxr-x--- 3 tomcat tomcat  4096 Oct 15  2018 work

ディレクトリのみ表示したい場合は、grepコマンドを使って結果をディレクトリのみにフィルタリングします。正規表現が使えるので以下のようにします。

[root@hostname apache-tomcat-8.5.34]# ls -l --color=always | grep '^d'
drwxr-x--- 2 tomcat tomcat  4096 Oct 15  2018 bin
drwx------ 3 tomcat tomcat  4096 Oct 15  2018 conf
drwxr-x--- 2 tomcat tomcat  4096 Oct 15  2018 lib
drwxr-x--- 2 tomcat tomcat 98304 Apr 21 22:27 logs
drwxr-x--- 2 tomcat tomcat  4096 Oct 15  2018 temp
drwxr-x--- 7 tomcat tomcat  4096 Oct 15  2018 webapps
drwxr-x--- 3 tomcat tomcat  4096 Oct 15  2018 work

–color=always オプションをつけると パイプで他のコマンドを繋いでもカラー表示してくれるので便利です。

ファイルのみ表示する方法

ファイルのみ表示したい場合は、grepコマンドの除外オプションを使います。-v オプションを指定すると条件にマッチしない行だけ表示することができます。

[root@hostname apache-tomcat-8.5.34]# ls -l --color=always | grep -v '^d'
total 240
-rw-r----- 1 tomcat tomcat 19539 Sep  5  2018 BUILDING.txt
-rw-r----- 1 tomcat tomcat  6090 Sep  5  2018 CONTRIBUTING.md
-rw-r----- 1 tomcat tomcat 57092 Sep  5  2018 LICENSE
-rw-r----- 1 tomcat tomcat  1726 Sep  5  2018 NOTICE
-rw-r----- 1 tomcat tomcat  3255 Sep  5  2018 README.md
-rw-r----- 1 tomcat tomcat  7142 Sep  5  2018 RELEASE-NOTES
-rw-r----- 1 tomcat tomcat 16262 Sep  5  2018 RUNNING.txt

シンボリックリンクのみを表示する方法

応用としてシンボリックリンクのみを表示することもできます。シンボリックリンクは 各行の先頭が l になります。以下のようにgrepの条件に指定しましょう。

[root@133-130-122-109 httpd]# ls -l --color=always | grep '^l'
lrwxrwxrwx 1 root root   19 Oct 15  2018 logs -> ../../var/log/httpd
lrwxrwxrwx 1 root root   29 Oct 15  2018 modules -> ../../usr/lib64/httpd/modules
lrwxrwxrwx 1 root root   10 Oct 15  2018 run -> /run/httpd

リナックスコマンドの知識は、プログラマにとって長く役立つ知識です。 私はこちらの書籍で一通り知識を抑えました。基本から丁寧に解説されています。