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

ls -d */

模式*/到底做什么?

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


当前回答

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

其他回答

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

对于所有没有子文件夹的文件夹:

find /home/alice/Documents -maxdepth 1 -type d

对于所有带子文件夹的文件夹:

find /home/alice/Documents -type d

*/是一个匹配当前目录中所有子目录的模式(*将匹配所有文件和子目录;/将其限制为目录)。类似地,要列出/home/alice/Documents下的所有子目录,请使用ls -d /home/alice/Documents/*/

实际的ls解决方案,包括到目录的符号链接

这里的许多答案实际上并不使用ls(或者仅在ls -d的普通意义上使用它,而使用通配符进行实际的子目录匹配。一个真正的ls解决方案是有用的,因为它允许使用ls选项来排序顺序等。

不包括符号链接

已经给出了一个使用ls的解决方案,但它与其他解决方案不同,因为它排除了到目录的符号链接:

ls -l | grep '^d'

(可能通过sed或awk管道来隔离文件名)

包括符号链接

在应该包含到目录的符号链接的情况下(可能更常见),我们可以使用ls的-p选项,这使得它在目录名(包括符号链接的目录名)后面附加一个斜杠字符:

ls -1p | grep '/$'

或者,去掉后面的斜杠:

ls -1p | grep '/$' | sed 's/\/$//'

我们可以根据需要向ls添加选项(如果使用长列表,则不再需要-1)。

注意:如果我们想要后面的斜杠,但不希望它们被grep高亮显示,我们可以通过将实际匹配的部分设为空来删除高亮显示:

ls -1p | grep -P '(?=/$)'

显示没有/的文件夹列表:

ls -d */|sed 's|[/]||g'