该命令列出当前路径下的目录:
ls -d */
模式*/到底做什么?
我们如何在上面的命令中给出绝对路径(例如ls -d /home/alice/Documents),只列出该路径下的目录?
该命令列出当前路径下的目录:
ls -d */
模式*/到底做什么?
我们如何在上面的命令中给出绝对路径(例如ls -d /home/alice/Documents),只列出该路径下的目录?
当前回答
这是我正在用的
ls -d1 /Directory/Path/*;
其他回答
*/是一个匹配当前目录中所有子目录的模式(*将匹配所有文件和子目录;/将其限制为目录)。类似地,要列出/home/alice/Documents下的所有子目录,请使用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}'
树命令在这里也非常有用。默认情况下,它将完整地显示所有文件和目录,并使用一些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 -1d /some/folder/*/ | awk -F "/" "{print \$(NF-1)}"
有四种方法可以做到这一点,每种方法都有不同的输出格式
1. 使用回声
例如:echo */, echo */*/ 以下是我得到的:
cs/ draft/ files/ hacks/ masters/ static/
cs/code/ files/images/ static/images/ static/stylesheets/
2. 只使用ls
例如:ls -d */ 这就是我得到的答案:
cs/ files/ masters/
draft/ hacks/ static/
或者作为列表(包含详细信息):ls -dl */
3.使用ls和grep
示例:ls -l | grep "^d" 以下是我得到的:
drwxr-xr-x 24 h staff 816 Jun 8 10:55 cs
drwxr-xr-x 6 h staff 204 Jun 8 10:55 draft
drwxr-xr-x 9 h staff 306 Jun 8 10:55 files
drwxr-xr-x 2 h staff 68 Jun 9 13:19 hacks
drwxr-xr-x 6 h staff 204 Jun 8 10:55 masters
drwxr-xr-x 4 h staff 136 Jun 8 10:55 static
4. Bash脚本(不推荐用于包含空格的文件名)
例如:$(ls -d */)中的i;执行echo ${i%%/};完成 以下是我得到的:
cs
draft
files
hacks
masters
static
如果你想用'/'作为结尾字符,命令将是:for i in $(ls -d */);执行echo ${i};完成
cs/
draft/
files/
hacks/
masters/
static/