“ls” コマンドで隠しファイルは出力したいが “.” と “..” は出力させない
Contents
はじめに
man
や --help
を調べればすぐわかりますが、使えると思いましたので投稿します。
検証環境
$ uname -moi
x86_64 x86_64 GNU/Linux
$ bash -version | head -n 1
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
ls
コマンド
オプション無しで実行
1ファイルしか見つかりません。
$ pwd
/root
$ ls | wc -l
1
$ ls
anaconda-ks.cfg
-a
オプション付きで実行
隠しファイル(ディレクトリを含む)を含めてファイル数を確認したいのですが、 カレントディレクトリを表す "." と 親ディレクトリを表す ".." が出力されてしまいます。
$ pwd
/root
$ ls -a | wc -l
10
$ ls -a
. .. .bash_logout .bash_profile .bashrc .cshrc .lesshst .pki .tcshrc anaconda-ks.cfg
-A
オプション付きで実行
隠しファイル(ディレクトリを含む)を含めて8ファイルであることがわかります。
$ pwd
/root
$ ls -A | wc -l
8
$ ls -A
.bash_logout .bash_profile .bashrc .cshrc .lesshst .pki .tcshrc anaconda-ks.cfg
注意:隠しディレクトリを除外sしたい場合
この例では、ディレクトリ( ex : .pki
)も対象として表示されてしまいます。
ファイルのみに限定したい場合はファイルの識別子を表示させる -F
オプションと組み合わせることで対処できます。
$ ls -F
anaconda-ks.cfg
# .pki/ ディレクトリの後方に "/" が表示され、ディレクトリであることがわかる
$ ls -A -F
.bash_logout .bash_profile .bashrc .cshrc .lesshst .pki/ .tcshrc anaconda-ks.cfg
# "/" で終わるものを除外
$ ls -A -F | grep -v '/$'
.bash_logout
.bash_profile
.bashrc
.cshrc
.lesshst
.tcshrc
anaconda-ks.cfg
最も、この方法であれば -a
オプションでも問題ないことになりますが。。。
$ ls -a -F | grep -v '/$'
.bash_logout
.bash_profile
.bashrc
.cshrc
.lesshst
.tcshrc
anaconda-ks.cfg
その他、 find
を使う方法もあります。
$ find . -maxdepth 1 -type f
./anaconda-ks.cfg
./.bash_profile
./.tcshrc
./.cshrc
./.bashrc
./.bash_logout
./.lesshst
ひとこと
今まではずっと find
方式でやっていたが、 ls -A
が使えることを学びました。
ディスカッション
コメント一覧
まだ、コメントがありません