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

ls -d */

模式*/到底做什么?

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


当前回答

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

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

或者用awk

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

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

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

其他回答

再加上一个完整的循环,检索每个文件夹的路径,使用Albert的答案和Gordans的组合。这应该很有用。

for i in $(ls -d /pathto/parent/folder/*/); do echo ${i%%/}; done

输出:

/pathto/parent/folder/childfolder1/
/pathto/parent/folder/childfolder2/
/pathto/parent/folder/childfolder3/
/pathto/parent/folder/childfolder4/
/pathto/parent/folder/childfolder5/
/pathto/parent/folder/childfolder6/
/pathto/parent/folder/childfolder7/
/pathto/parent/folder/childfolder8/

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

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

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

find /home/alice/Documents -type d

Ls和awk(不含grep)

No need to use grep since awk can perform regularexpressino check so it is enough to do this:

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

ls -l列出有权限的文件 Awk滤波器输出 '/^d/'正则表达式,只搜索以字母d开头的行(作为目录),并查看第一行-权限 {print}将打印所有列 {print $9}将只打印ls -l输出中的第9列(name)

非常简单明了

树命令在这里也非常有用。默认情况下,它将完整地显示所有文件和目录,并使用一些ASCII字符显示目录树。

$ tree
.
├── config.dat
├── data
│   ├── data1.bin
│   ├── data2.inf
│   └── sql
|   │   └── data3.sql
├── images
│   ├── background.jpg
│   ├── icon.gif
│   └── logo.jpg
├── program.exe
└── readme.txt

但是如果我们想要只获取目录,而不使用ASCII树,并且使用当前目录的完整路径,你可以这样做:

$ tree -dfi
.
./data
./data/sql
./images

论点是:

-d     List directories only.
-f     Prints the full path prefix for each file.
-i     Makes tree not print the indentation lines, useful when used in conjunction with the -f option.

如果你想要绝对路径,你可以从指定当前目录的完整路径开始:

$ tree -dfi "$(pwd)"
/home/alice/Documents
/home/alice/Documents/data
/home/alice/Documents/data/sql
/home/alice/Documents/images

为了限制子目录的数量,你可以用-L level来设置子目录的最大级别,例如:

$ tree -dfi -L 1 "$(pwd)"
/home/alice/Documents
/home/alice/Documents/data
/home/alice/Documents/images

更多的争论可以看到与人树。

仅列出目录:

ls -l | grep ^d

只列出文件:

ls -l | grep -v ^d 

或者你也可以这样做:

ls -ld */