LoginSignup
2

More than 1 year has passed since last update.

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

Posted at

バッチで必要になったので調べたついでにメモしておきます。

実施環境:
Linux
[testuser@testhost ~]$ uname -a
Linux testhost 4.18.0-147.8.1.el8_1.x86_64 #1 SMP Thu Apr 9 13:49:54 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
[testuser@testhost ~]$ echo $SHELL
/bin/bash

単にlsコマンドでディレクトリかどうかを判別する場合、"-l"オプションで先頭の文字が"d"であるかを確認すればディレクトリであるかは判別できます。
ただ、更新日時やサイズなど余分な情報も出てきてしまうため、ファイル名部分をバッチで利用する場合はこの方法ですと扱いづらいです。

Linux
[testuser@testhost ~]$ ls -l
-r-------- 1 testuser testgrp 0 Jun  6 13:04 test.conf
drwxr-xr-x 2 testuser testgrp 6 Jun  6 13:04 test_dir
--w------- 1 testuser testgrp 0 Jun  6 13:04 test.log
---x------ 1 testuser testgrp 0 Jun  6 13:04 test.sh

ではどうするのかというと、"-F"オプションを使用します。

Linux
[testuser@testhost ~]$ ls -F
test.conf  test_dir/  test.log  test.sh*

"-F"オプションを使用すると、対象のタイプに応じて末尾に記号が付与されます。
通常のファイルでは何も付与されませんが、実行権のあるファイルの場合は"*"が、ディレクトリの場合は"/"が付与されます。
そのため、grepをかけることでファイルのみ、ディレクトリのみの表示が可能となります。

Linux
[testuser@testhost ~]$ ls -F | grep -v /
test.conf
test.log
test.sh*
[testuser@testhost ~]$ ls -F | grep /
test_dir/

末尾の記号を削除したい場合はsedコマンドを使用します。

Linux
[testuser@testhost ~]$ ls -F | grep -v / | sed s/\*$//g
test.conf
test.log
test.sh
[testuser@testhost ~]$ ls -F | grep / | sed s/\\/$//g
test_dir

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
2