该命令列出当前路径下的目录:

ls -d */

模式*/到底做什么?

我们如何在上面的命令中给出绝对路径(例如ls -d /home/alice/Documents),只列出该路径下的目录?


当前回答

file * | grep directory

输出(在我的机器上)——

[root@rhel6 ~]# file * | grep directory
mongo-example-master:    directory
nostarch:                directory
scriptzz:                directory
splunk:                  directory
testdir:                 directory

以上输出可以通过使用cut进行进一步细化:

file * | grep directory | cut -d':' -f1
mongo-example-master
nostarch
scriptzz
splunk
testdir

* could be replaced with any path that's permitted
 file - determine file type
 grep - searches for string named directory
 -d - to specify a field delimiter
 -f1 - denotes field 1

其他回答

我只是把它添加到我的.bashrc文件中(如果你只需要/想要一个会话,你也可以在命令行上输入它):

alias lsd='ls -ld */'

然后lsd会产生想要的结果。

供您参考,如果您想以多行打印所有文件,您可以执行ls -1,这将以单独的行打印每个文件。 file1 file2 file3

一个当前目录的普通列表,它将是:

ls -1d */

如果你想要整理干净:

ls -1d */ | cut -c 1- | rev | cut -c 2- | rev | sort

记住:大写字符在排序中有不同的行为

这里是一个使用树的变种,它只在单独的行上输出目录名,是的,它很丑,但是,嘿,它工作。

tree -d | grep -E '^[├|└]' | cut -d ' ' -f2

或者用awk

tree -d | grep -E '^[├|└]' | awk '{print $2}'

然而,这可能更好,并且将保留目录名之后的/。

ls -l | awk '/^d/{print $9}'

回答最初的问题,*/和ls本身没有关系;它是由shell/Bash完成的,这个过程被称为globbing。

这就是为什么echo */和ls -d */输出相同的元素。(-d标志使ls输出目录名,而不是目录内容。)